JavaScript Loop Statement

JavaScript Loop Statement

When you hear loops, what image comes to your mind? yeah, you! The popular loops cereal was the first for me!

loops-img.jpg

As programmers, we often need to check or do something a certain number of times. This is when a loop becomes handy. According to Wikipedia, a loop is a programming structure that repeats a sequence of instructions until a specific condition is met.

JavaScript loops offer a quick and easy way to do something repeatedly. There are different kinds of loops, but they all do the same thing: they repeat an action some number of times. (Note that the number could be zero!).

Different Kinds of Loops

  • while - loops through a block of code while a specified condition is true.

  • do while - also loops through a block of code while a specified condition is true.

  • for - loops through a block of code a number of times.
  • for/of - loops through the values of an iterable object.
  • for/in - loops through the properties of an object.

The while loop

This loop can execute a block of code as long as a specified condition is true.

The while loop has the following syntax:

 while(condition) {
 //code to be executed
 }

While the condition is truthy, the code from the code in the loop block is executed. Let me give you an example:

let i = 0;          // initialization
while(i < 5) {    //condition check
 console.log(i);  
 i++;                 // step-definition
}
//output 0, 1, 2, 3, 4

In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 5, and when variable (i) becomes 5 the loop terminates/ breaks and it never gets to output 5.

###The ''do...while'' loop

This do...while loop will execute the code block at least once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. But if the condition is false, it breaks out after its first run.

The do...while loop has the following syntax:

do {
// code block to be executed
}while(condition)

Example: in the example below, variable(i) is 5; the loop logs variable(i) increments it before checking if the condition is true. Variable(i) is greater than 5, so the loop never runs again.

let i = 5;  //initialization
do {
  console.log(i); //code to be executed
  i++;    // step-definition: increment
}while(i < 5) //condition

The for loop

The for statement consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop. This loop is a more complex and flexible loop when iterating in JavaScript.

It has the following syntax.

for (initialization; condition; step-definition) {
  // code to be executed
}
  • Initialization: a variable is created and initialized before the execution of the code block.
  • Condition: defines the condition for executing the code block.
  • Step-definition: a step is taken (every time) after the code block has been executed. it could be to increment or to decrement the variable.
const arr = ['shoes', 'bags', 'perfumes', 'dresses'];

for(let i = 0; i < arr.length; i++) {
  console.log('**' + arr[i] + '**'); 
}
//output **shoes**, **bags**, **perfumes**, **dresses**

From the example above, you can read:

We created a variable before the loop starts (let i = 0).

We defined the condition for the loop to run (i < arr.length). If the condition returns true, the loop will start over again, if it returns false, the loop terminates.

We increase the value of (i++) each time the code block in the loop has been executed.

In this loop, any of its three statements can be skipped but not even one semi-colon should be skipped. Example: The example below is used to run an infinite loop.

for(; ;) {
//code to be executed.
}

The ''for...of'' loop

The for...of loop creates a loop iterating over iterable object. This loop can loop through arrays and strings with no problem at all.

It has the following syntax.

for (variable of iterable) {
  // code block to be executed
}

Example: Let's loop through an array with a for...of loop

let numbers = [5, 6, 57, 49, 18];
for(const num of numbers) {
  console.log(num * 2);
}
//output 10, 12, 114, 98, 36

Example: Let's loop through a string with a for...of loop .

const string = 'JavaScript';
for(const substr of string) {
  console.log(substr);
}

The ''For..in'' loop

This loops through the properties of an object. It has the following syntax.

for (key in object) {
  // code to be executed
}

Iterating over an object.

Remember we can access the keys of an object with either dot notation obj.key or bracket notation obj[key].

The for...in loop iterates over an object. Each iteration returns a key. You can output the key like we did below or use the key to access the value like this obj[key].

Example: Let's iterate over the person object to get the keys/properties of the object.

const person = {
  name: 'orbie',
  age: 22,
  career : 'Programming',
  newSkills: ['git', 'bootstrap', 'javascript', 'Linux']
}

for(const key in person) {
 console.log(key);
}
//output name, age, career, newSkills

Final Thoughts

Use the for loop for an iteration that is complex.

Use the `for...of loop for arrays.

When it comes to objects, there many built-in methods to iterate over keys and values like the Object.keys(), Object.values() and Object.entries(). When contemplating of a loop to use for objects, use the for...in loop for objects.

If you forget to put a step-definition (increment/decrement) inside the loop, the loop will never terminate! Instead, you'll be stuck in what's called an infinite loop! So always make sure that you set an expression that will terminate/break the loop.

Thank you for reading. If you would like a more thorough look at loops, then these resources are for you:

(javascript.info/while-for) MDN JS Loops and Iteration W3schools JS Loops