Understanding for loop in javascript array - Meteorio

Understanding for loop in javascript array

| 3 years ago

You must have heard of loops before if you are into programming. Loops are basically used to either execute similar code multiple times or to work with iterables like an array. If you are new to javascript and are wondering how to work with loops and arrays in javascript, then stay tuned, we will dive deep into them.

Don’t forget to checkout our article on error and exception handling in javascript

For loop in javascript arrays

Let’s discuss a situation. You have an array of planets in our solar system and you want them to be printed in the browser’s console window along with their position in the solar system. Here are two different ways to do it.

Method 1


var planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"];
console.log("1." + planets[0]);
console.log("2." + planets[1]);
console.log("3." + planets[2]);
console.log("4." + planets[3]);
console.log("5." + planets[4]);
console.log("6." + planets[5]);
console.log("7." + planets[6]);
console.log("8." + planets[7]);
console.log("9." + planets[8]);

You must be aware that array indexes in javascript start from 0. So, to get the first element of an array, the syntax would be array_name[0], similarly for the second element it would be array_name[1] and so on. As, we need to print the name of all nine planets in our solar system, we are having to write a console.log() statement nine times. Ahh, isn’t it lengthy and boring? Why can’t we have something cooler and easier.

Method 2


var planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"];
for (var i = 0; i < planets.length; i++) {
  console.log(i + 1 + ". " + planets[i]);
}

This method outputs the exact same result as Method 1 but with less code. The for loop basically loops through every element of the array, gets the current loop number and adds 1 to it to make it a serial number(index of javascript arrays starts from 0), uses the same loop number to fetch an element from the array and logs it in the console window.

So let’s start with the basics of a for loop in javascript

Syntax


for(statement 1, statement 2, statement 3){
// You code here
}

Key points

  1. Statement 1 executes single time before executing the code inside the loop
  2. Statement 1 is generally used to initialize a variable to be used inside the loop
Example

for (var i = 0; i < 5; i++) {
  console.log("The current index is: " + i);
}
  1. You can assign as many variables as you want in Statement 1 like (var i=0, j=2). Also Statement 1 is optional
Example

for (var i = 0, j = 1; i < 5; i++) {
  console.log("The current indexes are: " + i + " " + j);
  j++;
}
  1. Statement 2 is generally used for condition checking. If the Statement 2 returns true, the loop executes, if returns false, it won’t. Anyways, Statement 2 is optional as well. So, when you plan to avoid Statement 2, make sure you have a break statement inside the loop or else it will lead to an infinite loop.
Example

for (var i = 0;; i++) {
  console.log("This will execute first and last time");
  break; // without break; the loop will run forever
}
  1. Statement 3 is used to either increment(i++) or decrement(i–). But, this statement is optional as well. You can even choose not to have it and do increment or decrement inside the loop.
  2. All three statements (Statement 1, Statement 2, Statement 3) are optional.
Example

for (;;) {
  console.log("This will execute first and last time");
  break; // without break; the loop will run forever
}

Continue statement in for loop

Syntax

continue ;
continue [labelname];

Key points

  1. When used in a for loop, continue statement terminates the current iteration and moves to the next iteration.
  2. After the continue statement, the control is moved to the third statement in the for loop i.e the increment or decrement statement.
  3. Continue statement is applied to the statement that is identified with the labelname, when it is used with labelname. labelname in the continue statement is optional.
Example

for (var i = 0; i < 5; i++) {
  if (i == 2) continue;
  console.log("The current index: " + i);
}

Loop1: // The first for loop is labeled "Loop1"
  for (i = 0; i < 3; i++) {
    Loop2: // The second for loop is labeled "Loop2"
      for (j = 4; j < 8; j++) {
        if (j === 7) {
          continue Loop2;
        }
        console.log("The values of i and j are: " + i + " " + j);
      }
  }

Break statement in for loop

Syntax

break ;
break [labelname];

Key points

  1. Break statement is used to terminate the loop completely.
  2. Break statement terminates the innermost enclosed loop when used inside nested loop.
  3. When used with the labelname, break statement terminates to the specified labelname statement.
Example

for (var i = 0; i < 5; i++) {
  if (i == 2) break;
  console.log("The current index: " + i);
}

For loop in javascript array

For/Of loop

The For/Of in javascript, loops through every element of an iterable Data structure.
The Data structures can be Arrays, String etc.

Syntax

for (item of iterable) {
  // You code here
}

Key points

  1. In the syntax above, for every iteration the value of each element is assigned to the item variable. The item variable can be declared with var,let or const.
  2. Iterable is the data structure that can be iterated like Array, Strings etc.
Example

var names = ['Prabhat', 'Mukesh', 'Ankita'];
for (var x of names) {
  console.log(x)
}

Conclusion

Loops are very handy when it comes to work with iterables like Array.I hope the fundamentals of a for loop in Javascript is clear to you by now. If you want to discuss or have anything to say, don’t feel shy to hit the comments.

Happy Coding !!!

Adverts *