In today’s lessons, I investigated the for statement.
To use the for statement, you type in for(3 statements go here), then the typical { and } (example shown at the end of entry I swear!). The code inside the curly mustache brackets execute if the 3 statements in your parenthesis are true.
One thing to remind anyone reading is DO NOT GO HEAVY WITH SEMICOLONS. If you run for loops with semi-colons in the wrong places, you’ll get operand or illegal xml errors.
Also another thing to keep in mind is to make sure your statements in your for loop are logical. If they aren’t, you risk running infinite loops that will crash out your internet explorer when you test run code.
Inside the for loop, you have parenthesis that tell javascript what makes your statement true.
As an example use the variable “a”.
(a=1; a=<5; a++)
Notice that I did not put a semicolon after the “a++”
If you do, you are telling javascript to end your for statement there and you do not want that to happen.
The first a says, hey let’s start at 1.
The second is a conditional, it says, hey only run the code until a is less than or equal to 5.
The third, tells us that starting from 1, javascript will add 1 to 1 and poop out a number.
If you run your code correct, you will get prompts that say
1
2
3
4
5
It starts and ends with 5, adding 1 each line just as we told it to. Another thing to keep in mind is the console.log statement. We can make it print this out by
for(a=1; a<=5; a++)
{
console.log(a);
}
Notice semicolon at end of console statement.
Tweaking it you can make it start at 3, 100, 1000, or go in increments of 5, or use “-=” to make it decrements of 5 or whatever you choose!
