For Loops
For
loops are used to iterate over a sequence of elements. They are used when a code block needs to be repeatedly executed a known number of times.
In JavaScript, for
loops are set by specifying three statements after the for
keyword in parenthesis.
- The first statement sets a variable before the loop starts. This statement is executed only once before the execution of loop.
- The second statement defines a condition for the loop, which is continuously checked during the execution.
- The third statement is responsible for changing the value (such as incrementing or decrementing) of the variable every time the code block for the loop is executed.
The variable initialized in the first statement is important as that same variable is used in second and third statements to specify the condition and value change. It can also be used within the loop block to access the elements. Let's understand this with an example.
Suppose you want to print a list of numbers from 0 to 9.
1//prints a sequence of numbers from 0 to 9
2for (var i = 0; i < 10; i++){
3 console.log(i);
4}
The usefulness of loops come into play when we use them on sequences such as strings or arrays. By accessing the length of sequences using the .length
property, we can access each element in the given sequence.
In the below example, the loop is executed 5 times, and each time an element from the array is accessed using indexing to print all elements in the array.
1//prints all values in the vegetables list using indices
2var vegetables = ["tomato", "potato", "onion", "lettuce", "carrot"]
3for (var i = 0; i < vegetables.length; i++){
4 console.log(vegetables[i])
5}