DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 968,873 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for In JS how do you know the right condition to use inside your for loop?
scothinks
scothinks

Posted on

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

I'm new to JavaScript and I've been struggling with iterating with for loops.

The early classes were easy to understand when the condition was simply i < 9 or i > 9.

The issue I have now is knowing when to use conditions like i < arr.length for example.

Many times when I do JS challenges and check the solution for challenges I fail, I see these type of conditions and I don't know why one condition is used instead of another.

Can anyone help me out with this, please?

Top comments (10)

Collapse
 
pedrohasantiago profile image
Pedro S • Edited on

So, it all depends on what you want to do. I'd suggest you first start with while loops, and then you move on to for loops.

Let's say you want to print "hey" 5 times:

let times = 0;
while (times < 5) {
  console.log('hey');
  times++;
}
Enter fullscreen mode Exit fullscreen mode

Your times variable start as 0. That's < 5, so you print "hey". Then times is 1; that's < 5, so you print "hey" again. You keep doing that and only stop when times == 5; then you've printed "hey" 5 times (remember we started at 0 πŸ˜‰).

When you use a for loop, the commands related to controlling the loop are bundled up after the for keyword, but they are all the same.

for (let times = 0; times < 5; times++) {
  console.log('hey');
}
Enter fullscreen mode Exit fullscreen mode

This will do the same thing. let i = 0 is executed first and only once; then, the code inside the brackets is executed if i < 5; at the end of each execution, i++ is called and the condition is checked again.

When dealing with arrays, you want to cycle through the indices in it:

let myArray = ['zeroth', 'first', 'second', 'third', 'fourth', 'fifth'];
// The indices in the array go from 0 until 5. Let's get each one of those!
let currentIndex = 0; // Starting at the first index in the array
while (currentIndex < myArray.length) { // Stopping when we reach the number 6
  console.log(myArray[currentIndex]);
  currentIndex++;
}
Enter fullscreen mode Exit fullscreen mode

Notice that an array [0] has an element at index 0 and a length of 1; an array [1, 2] has elements at indices 0 and 1 and a length of 2... The length is always 1 more than the last index, so you can use that to iterate on all the elements of any array.

In for loop style:

let myArray = ['zeroth', 'first', 'second', 'third', 'fourth', 'fifth'];
for (let currentIndex = 0; currentIndex < myArray.length; currentIndex++) {
  console.log(myArray[currentIndex]);
}
Enter fullscreen mode Exit fullscreen mode

When dealing with arrays, most of the times you start at 0, go all the way until before you reach the array length, adding 1 on each step. If you want to go from the end of an array to its beginning, it's the opposite:

let myArray = ['zeroth', 'first', 'second', 'third', 'fourth', 'fifth'];
for (let currentIndex = myArray.length - 1; currentIndex > -1; currentIndex--) {
  console.log(myArray[currentIndex]);
}
Enter fullscreen mode Exit fullscreen mode

You could also have written the condition in this last for loop as currentIndex >= 0. The important is executing the code when you are at index 0.

If you don't know the condition you need, stop and think about what you want to do. You need to do something a certain number of times? Then the condition will depend on the maximum number of times. You need to access the elements in an array? Then the condition will depend on the size of the array.

I hope this helps πŸ˜„

Collapse
 
scothinks profile image
scothinks Author

This helps a lot. I'll practice some more. Thank you.

Collapse
 
hi_artem profile image
Artem

If you struggle with it, you are no alone.

That's why modern languages introduces a concept of iterator or iterator methods. In JS, you can use forEach to achieve similar purpose of a for loop. There are also for ... in and for ... of loops where you don't have to care about indexes.

Collapse
 
scothinks profile image
scothinks Author

Thank you!

Collapse
 
kalashin1 profile image
Kinanee Samson • Edited on

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 Author

Quite useful. Thank you.

Collapse
 
leob profile image
leob • Edited on

Like this?

var colors = ['red', 'green', 'blue'];

for (var i = 0, len = colors.length; i < len; i++) {
  var color = colors[i];
  console.log('Color:', color);
}

console.log('Done!');
Enter fullscreen mode Exit fullscreen mode

That's more or less how I do it, putting the length in a variable at the start for performance reasons (but probably that's more theoretical than real, performance-wise).

If you have a second, nested for loop then don't forget to choose a different counter variable (e.g. j instead of i).

Alternatively there's also for ... in and for ... of, in slightly newer versions of Javascript.

Collapse
 
scothinks profile image
scothinks Author

Hmm never seen it done like this before. And it makes sense. Thank you.

Collapse
 
_bkern profile image
Barry

The trouble with challenges is someone most likely will always have a better solution than you. That's totally fine. If yours works and you are just starting - high five yourself you did it!. Overtime with experience you might learn the way you have been doing things could be improved/optimized but leave that for later.

Collapse
 
scothinks profile image
scothinks Author

I appreciate the boost. Thank you.

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs