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.

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).
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! Break statement : When i hits 0 here, it will stop the loop.