cover-img

JavaScript Loops

20 January, 2023

14

14

1

Loop

In programming, a loop is a control structure that repeatedly executes a code block until a specific condition is met. There are several loops, such as for loops, while loops, and do-while loops, each with slightly different syntax and behaviour. Loops are used to perform repetitive tasks, such as iterating through the elements of an array or repeating a particular action until a user input meets specific criteria.

There are several ways to perform loops in JavaScript. Here are a few examples:

The for Loop

This is used to iterate over a sequence of values, such as an array. The syntax is as follows:

for (initialization; condition; increment/decrement) {
// code to be executed
}

Here is an example of a for loop that counts from 1 to 10:

for (let i = 1; i <= 10; i++) {
console.log(i);
}

The for...of loop

This is used to iterate over the values in an iterable object, such as an array or string. The syntax is as follows:

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

Here is an example of a for...of loop that prints the elements of an array:

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

for (const color of colors) {
console.log(color);
}

The while Loop

This is used repeatedly executing a code block while a particular condition is true. The syntax is as follows:

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

Here is an example of a while loop that counts from 1 to 10:

let i = 1;

while (i <= 10) {
console.log(i);
i++;
}

The for-in Loop

A for-in loop is used to iterate over the properties of an object. The syntax is as follows:

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

Here is an example of a for-in loop that logs the properties of an object:

const person = {
name: 'John',
age: 30,
occupation: 'teacher'
};

for (const key in person) {
console.log(key + ': ' + person[key]);
}

This will output the following:

name: John
age: 30
occupation: teacher

It's important to note that the for-in loop will iterate over all the object's enumerable properties, including those inherited through the prototype chain. Suppose you only want to iterate over the object's properties. In that case, you can use the Object.keys() method to get an array of the object's enumerable properties and then use a for-of loop or a forEach() loop to iterate over the array.

Object.keys(person).forEach(function(key) {
console.log(key + ': ' + person[key]);
});

The do...while Loop

This is similar to a while loop but will consistently execute the code block at least once because the condition is checked after the loop body is executed. The syntax is as follows:

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

Here is an example of a do...while loop that counts from 1 to 10:

let i = 1;

do {
console.log(i);
i++;
} while (i <= 10);

14

14

1

ShowwcaseHQ
Showwcase is where developers hang out and find new opportunities together as a community

More Articles