JavaScript Home

Arrays and For Loops

Variable Review

A variable is something you define in your program that can store a number or word that can change over time. Think of it like a backpack. You might have a computer in your backpack, but you can change the contents whenever you like. Variables are used by programmers to store and change information.

You can write a variable in javascript like this

var backpack="banana"; 

Here, backpack is the identifier. The equal sign is the assignment operator and it assigns the identifier information (in this case, the word "banana").

Variable Assignment

Variables can be text values (referred to as strings), or numbers. Strings are always inside single or double quotes. There are different ways of writing variable (In documentation you will encounter variable names let and const, as well. We will use var, because it is straightforward, and the w3school uses it).

var pi = 3.14;
var userMessage = "Message received!";

Variable Arithmetic

You can use arithmetic operators to increment, decrement, multiply, add, subtract, divide variables with number values - and to manipulate strings like we used in the previous lesson (concatenation of a string and variable). You can use the javascript script tags <script></script>in your html document body to run these tests:

Variable Arithmetic Examples
HTML:

<p id="demo"></p>
<h2>Subtracting variables </h2>
<p id="demo2"></p>
<h2>Expressions </h2>
<p id="demo3"></p>

<script>
var w = 1    
var x = 2 + 1;
var y = x - w;
var z = (5+5) * x
document.getElementById("demo").innerHTML = x;
document.getElementById("demo2").innerHTML = y;
document.getElementById("demo3").innerHTML = z;
</script>
Adding numbers: var x = 2 + 1
Subtracting variables: var y = x - w
Expressions: var z = (5+5) * x

The increment operator (++) increments numbers, and the decrement operator (--) decrements numbers. You will often see these operators in functions that count user interactions.

var x = 5;
x++;
var z = x; 

In this case, z will equal to 6, and increment by in each time x++ is called.

More on Javascript arithmetic at W3schools

Arrays

Arrays are a type of data structure that allow you to store or index multiple items and call upon them later.

var fruits = ["Banana", "Orange", "Apple", "Mango"];

To test out different array concepts, lets imagine you have some test paragraphs in an html file:


<p id="arrayDemo"></p>
<p id="arrayDemo2"></p>
<p id="arrayDemo3"></p>    

You can access an array, by referring to the index number of the item you want. Note that index numbers always start at 0. For example, if I want to access my Banana, I would write: fruits[0]. If I want my Apple, I would write fruits[2]. Here's some Javascript code for my test

document.getElementById("arrayDemo").innerHTML = fruits[0];

If want my full array, I can write the following:

document.getElementById("arrayDemo2").innerHTML = fruits;
This will give me the following in my HTML: Banana, Orange, Apple, Mango

Now, because my array is a special kind of object, if I want to know how long my array is, I can use the length property to return the length of an array (the number of array elements). Note that the length property is always one more than the highest array index (because the index starts at 0).

document.getElementById("arrayDemo3").innerHTML = fruits.length;  // the length of fruits is 4
Index 0, or fruits[0]:
Full array, or fruits:
Array length, or fruits.length:

Looping through Arrays (for loops)

The best way to loop through an array is using a for loop. And using arrays and for loops, we can dynamically create content on our pages using Javascript. In the following example, I'm going to make an unordered list by looping through my fruit array, and adding them for my html. Here is the HTML and Javascript:

<p id="forloop"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var fLen = fruits.length;
var i;
var ul = "<ul>";

for (i = 0; i < fLen; i++) {
  ul += "<li>" + fruits[i] + "</li>"; //note that the += assignment operator can also be used to add (concatenate) strings
}

ul + "</ul>";

document.getElementById("forloop").innerHTML = ul;
</script>

The above example will produce the following list:

Next: FTP
Previous: Debugging

Adding to previous examples

In our previous example, we changed the background color to yellow...Lets say we wanted to create an accessible color scheme that renders all of our content in a high contrast pallete. Changing the background color is easy because it is one item in our DOM object. If we want to change all of our paragraphs and headings too, we will call up an array of all the paragraphs in our DOM object, and loop through them to change them. Here is how we can do that:

<button type="button" onclick="black()">high contrast mode</button>
<p id="message" aria-live="assertive" id="color"></p>

    <script>
        function black() {
            document.body.style.backgroundColor = "black";
            var l =document.querySelectorAll("body");
            y=l.length;
            for (i=0; i< y;i++){
           l[i].style.color="white";
            }
            document.getElementById("message").innerHTML = "you are in high contrast mode!";
        }

    </script>

looping example

For a more in-depth look and training in JavaScript, please visit freecodecamp, and try out their course content! Freecodecamp unit on Javascript