Thursday, August 7, 2014

JavaScript: Arrays, Arrays with Loops, Continue, and Break

Creating an array: A very simple version of an array will start with var for variable and the name of you array (here it is: , but you can name it anything you like!). The first one in brackets will automatically be 0, as many programs are "zero-based" -- meaning start counting at 0, instead of 1. Let's say you have an Id of "example" and already declared a script. Then 1 will be cookies, 2 is salad.. And so on if you wanted more inside of your array. The code below would print: "Mint Chocolate Ice Cream" and "Cookies" only. Note how we have to call each one individually, but we don't have to call them all.
var food = ["Mint Chocolate Ice Cream", "Cookies", "Salad"];
document.getElementById("example").innerHTML = food[0];
document.getElementById("example").innerHTML = food[1];

Using an array in a loop: Now we can loop over all of the things in an array (or only things less/greater than etc.. If you wanted).

var myFoodArray = ["Chocolate", "Ice Cream", "Cookies"];
for (var i = 0; i < 100; i++)
{
    console.log("I like to eat: " + myFoodArray[i] + ".");
}

From the above your output would be:
I like to eat Chocolate.
I like to eat Ice Cream.
I like to eat Cookies.

Continue statement: If the loop keeps running, you are good and the number is even. If you cannot fulfill the "if" statement, it will break and skip the whole bracketed "if" part and go to the console.log portion. Since it would only break if you have an odd number, this is a good way and time to print as such!

for (var i = 0; i < 100; i++)
{
    // check that the number is even
    if (i % 2 == 0)
    {
         continue;
    }
    // if we got here, then i is odd.
    console.log(i + " is an odd number.");
}
Break statement : When i hits 0 here, it will stop the loop.
var i = 99;
while (true)
{
    console.log(i + "red balloons");
    i -= 1;
    if (i == 0)
    {
        break;
    }
}