JavaScript For Loop
A for loop in JavaScript is a type of loop that allows you to iterate over a block of code a certain number of times.
The syntax of a for loop is as follows:
for (initialization; condition; iteration) {
// code to be executed
}
Explanation:
initialization: This is typically used to initialize a counter variable that is used to keep track of how many times the loop has executed. This is only executed once before the loop starts.condition: This is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed. If the condition is false, the loop exits.iteration: This is usually used to increment or decrement the counter variable. This is executed after each iteration of the loop.
Here's an example of a for loop that prints the numbers 0 through 4 to the console:
for (let i = 0; i < 5; i++) {
console.log(i);
}
In this example:
let i = 0initializes the counter variableito 0.i < 5is the condition that checks ifiis less than 5.- As long as i is less than 5, the loop will continue to execute. i++ increments
iby 1 after each iteration of the loop. - Inside the loop,
console.log(i)prints the current value ofito the console.
Different Kinds of Loops
There are several different kinds of loops in JavaScript that you can use to repeat a block of code a certain number of times or until a certain condition is met.
Some of the most commonly used loops are:
forloop: This is the most commonly used loop in JavaScript. It allows you to iterate over a block of code a specific number of times. See the previous answerforan example of aforloop.whileloop: This loop will continue to execute as long as the condition is true.do-whileloop: This loop is similar to thewhileloop, but it will always execute at least once, even if the condition is false.for...inloop: This loop is used to iterate over the properties of an object.**for...ofloop:** Thefor...ofloop is a type of loop in JavaScript that allows you to iterate over the elements of an iterable object, such as an array or a string.
The For Loop example
You can also use a for loop to iterate over the elements of an array:
Editor
In this example:
- HTML code creates an unordered list (
<ul>) with an ID offruitsList. - Uses JavaScript to iterate over the
fruitsarray and create a list item (<li>) for each fruit. - The text content of each list item is set to the corresponding fruit from the array using
innerText, and the list item is added to theulelement usingappendChild.