Programming Tutorials

for, for..of, and for..in loops in JavaScript

By: Tanya in Javascript Tutorials on 2023-04-25  

In JavaScript, there are several ways to loop through arrays and objects. Here's an overview of the for, for..of, and for..in loops:

  1. for loop:

The basic for loop is used to iterate over a range of numbers or indices in an array.

Syntax:

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

Example:

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

The for..of loop is used to iterate over the values of an iterable object, such as an array or a string.

Syntax:

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

Example:

const arr = ['apple', 'banana', 'orange'];

for (const fruit of arr) {
  console.log(fruit);
}

Output:

apple
banana
orange
  1. for..in loop:

The for..in loop is used to iterate over the properties of an object, such as the keys in a key-value pair.

Syntax:

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

Example:

const person = {
  name: 'John',
  age: 30,
  gender: 'male'
};

for (const prop in person) {
  console.log(`${prop}: ${person[prop]}`);
}

Note that this line console.log(`${prop}: ${person[prop]}`); is using a Template Literal

Output:

name: John
age: 30
gender: male





Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)