DEV Community

Discussion on: In JS how do you know the right condition to use inside your for loop?

Collapse
 
kalashin1 profile image
Kinanee Samson • Edited

You use array.length in a for loop when you want to iterate over the array and do something with the items inside the array. If the process you want to iterate is not concerned with the array or the values inside it, I would suggest you don't use it. Say we want to print the values inside an array one after the other we could do it like this.

const myArray = [1,2,3,4,5]
//then using for
for(var i = 0; i  < myArray.length;  i++)
{
  console.log(i) 
  //prints out 1, 2, 3, 4, 5
}
Enter fullscreen mode Exit fullscreen mode

The thing is that with for loops you need to pass a starter counter, that is a variable that specifies where to begin the loop from, that is why we set i = 0. The next thing the for loop needs is a way to specify the end of the iteration and that is why use the array length. which returns a number that is the equivalent of the number of items in the array. The last part is the i++ which tells the for loop to increment the initial value after each iteration of the block of the code in the body of the loop. Hope this is useful to you

Collapse
 
scothinks profile image
scothinks

Quite useful. Thank you.