For Loops in Javascript

This is fairly simple, we're creating a loop, something that is done over and over. The for bit tells us how long to do it for.

A for loop looks like this:

for (something; something < else; something and math) {
    stuff happens;

The space between the brackets is where the magic happens. Don't forget, those are semicolons separating the bits, commas won't work! Here's what they do:

  1. Start : something
    • This is the initial value of your for loop - a variable. It changes during the loop.
  2. End: something < else
    • This determines how long the loop keeps on looping. We're using some math operator to create boolean for every loop. As long as the boolean is true the loop will run. As soon as it's false the loop ends.
    • If it never turns "false" the loop will just keep on going - not good! - and you'll have what's known as an "infinite loop" which pretty much crashes your browser. Which is why the next little widget is so important.
  3. Control: something and math
    • The control is used to change the variable. For example something++ would add increase the variable value by 1 each time the loop runs.
    • Note: writing something++ is equivalent to writing something + 1

Okay, so let's put it in basic English with a simple numerical example. Let's say we start with a variable called myNumber and assign it a value of 10. We want the loop to run as long as our variable is more than or equal to 2 and we're subtracting 1 on each loop. The loop would look something like this:

var myNumber = 10;
for (myNumber; myNumber >= 2; myNumber--) {
    stuff happens;