For Loops in JavaScript

For loops are used to repeat sections of code without having to retype the code. You can write code once and have it repeat a certain number of times depending on how the condition of the for loop. For loops have iterators, a condition and an increment. The iterator is the variable used to store the current number, the condition determines when to stop repeating, and the increment is used to change the number after each iterative loop.

The below code snippet shows a basic for loop written in JavaScript. The iterator, condition, and increment are enclosed within parenthesis and separated with semi-colons. The first section is the creation of the iterator, this could be an existing variable but in this example a new variable is created. The iterator is call ‘i’ and is initialised with the value of 0. The condition, which is the next section enclosed in the parenthesis, is checking that the variable ‘i’ is less than the number 10, and the last section increments the variable ‘i’ by 1. The last section, the double addition ‘++’ symbol, is shorthand available in most programming languages that will take a variable and add 1 to it, there is also shorthand to minus 1 from a variable which is two hyphens/subtract ‘–‘ symbols.

The code within a for loop, which is enclosed in curly brackets, will be executed as long as the condition of the for loop succeeds. This means, that while the variable ‘i’ is less than the number 10 the log statement will be repeated. The final part of the loop increments the variable by 1, this happens at the end of each successful loop. This means the first number that is logged with be 0, then 1, then 2, all the way up to the number 9.

Shorthand decrementing can also be used within for loops. This means that instead of counting up from the number 0 we can count backwards. The for loop shown below starts the number 10 and will count backwards logging the number 10, 9, 8, all the way to 0. The reason the number 0 is logged also is because the condition is checking if the iterator is above or equal to the number 0, which means when the iterator is equal to the number 0 than the loop is executed.

Incrementing is not limited to only the auto incrementation. You can modify the final part of the for loop to be any mathematical equation, so you could add more numbers, multiply by some factor, or anything mathematical. The below for loop will log the following numbers: 0, 2, 4, 6, 8, 10. Look through the below code, and the elements of the for loop, you should be able to see why these are the numbers are logged out.

For loops can be quite complicated for new developers to understand, due to amount of syntax that is required to create one. Remember, they can only be used for numbers, and looping in regards to the value of a number. They contain all the elements of the loop inside the parenthesis, the iterator, the condition, and the increment operation.

Leave a Reply