loop in javascript

In JavaScript Language, We can iterate through an enumerable properties of an given object by using for...in loop. This loop will go through each element execute a block of code in the object.

for…in object javascript

Syntax

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

Below is an example on How to use for...in loop to iterate the properties in an object {}:

const obj = {
  name: "Rajat",
  age: 27,
  country: "India"
};

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

Output of above code:

name: Rajat
age: 27
country: India

Here the for...in loop is similar to that of for...of loop, which is used to iterate over the values of an iterable object, For Example an array. But Note that, the for...in loop iterates over the properties of an object, while the for...of loop iterates over the values.

Here for..in loop will iterate the properties of the object and print the key and value of each property in the object defined.

for..of array javascript

Below is an example on how to make use of for...of loop to iterate value of an array:

const arr = [5, 2, 1, 3, 4];

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

This will output the following:

5
2
1
3
4