DEV Community

Arya Krishna
Arya Krishna

Posted on

For-Loop in JavaScript

There's a limitation of only accessing arrays based on the index value. We would be repeating a lot of code when we are doing this. Instead we can use a for-loop to execute code more than once.

One of the primary reasons for us to use our for-loop is because we can loop over the items in our array. For-loops are often used to iterate over arrays.For-loops are just iterative repeatable blocks of code that is going to run a certain number of times. How many times our loop is going to run is based on for-loop definition.

Let's breakdown our for-loop a bit more in detail.

Every for loop begins with a FOR keyword followed by a set of parentheses. This looks familiar to our if statements. Followed by parentheses there will be curly brackets.

for (
var i = 0;i < 5; i++) {
This block of code will run each time
}
Enter fullscreen mode Exit fullscreen mode

Going into our for-loop we get three parts. In the block of code above var i = 0 is our declarative statement - where we come and declare our variables which can be used through out the process. We are going to start at position zero is what we are defining here.i < 5 determines when our loop should be broken. In other words our condition no longer evaluates to true when i is less than 5. This brings us to the last part i++ where we increment or modify our pointer to change how we are moving through the loop. i++ means i = i+1 which then brings us back to the condition check.

In for-loop we also take the advantage of arrays length property. We loop until we are one less than the array length. In a for-loop we are not looping over an array but we are looping over a position to point in to each part of our array from start to finish.

Top comments (0)