DEV Community

Cover image for JavaScript for loop

JavaScript for loop

For Loop is one of the most used concepts in JavaScript. It helps you to perform repetitive actions.
It has amazing parts.
for(let i =1; i<=5;i++){
//you can write any code you want
console.log("life is awesome");
}

The first part (let i =1) is where you declare your variable. Just like the way you usually declare variables. It's much safe to use let and var rather than const because, const variables can't be resigned. Your variable could be anything but alot of people are using "i".

If you want to loop through an array, the value of your variable should be 0, which is the first element in an array.

The second part is the logic part (i<=5).After each iteration, it checks whether "i" is less than 5 or equal to 5. If it's less than 5, The third part will add 1 to the variable till it's up to 5 or any number you specified. If the third part is missing, then the loop will continue till eternity because the condition will always be true. The logic must be false before the iteration will stop.

That's the basic explanation of for loop in JavaScript.

Top comments (0)