JavaScript for...in loop with Example

JavaScript for…in loop with Example

In this tutorial, you will learn about JavaScript for…in loop with the help of examples.

The for…in statement combination iterates (loops) across an object’s properties. For each property, the code block within the loop is executed once.

  • JavaScript provides several types of loops: for loops through a block of code several times. for/in – loops over an object’s properties. for/of – iterates over the values of an iterable object.
  • The primary distinction between them is in what they iterate over. The for…in statement iterates over an object’s enumerable string properties, whereas the for…of statement iterates over values defined by the iterable object to be iterated over.

JavaScript for…in loop

The syntax of the for..in loop is:

for (key in object) {
    // body of for...in
}

The key variable is assigned a key during each loop iteration. The loop is repeated for all object properties.

Note: Once you have the keys, you can quickly discover the values that correspond to them.

Example 1: Iterate Through an Object

const student = {
    name: 'Monica',
    class: 7,
    age: 12
}

// using for...in
for ( let key in student ) {

    // display the properties
    console.log(`${key} => ${student[key]}`);
}

Output:

name => Monica
class => 7
age => 12

The for…in loop is used in the preceding software to iterate through the student object and print all of its properties.

The variable key is given the object key.
To get the value of the key, use student[key].

Example 2: Update Values of Properties

const salaries= {
    Jack : 24000,
    Paul : 34000,
    Monica : 55000
}

// using for...in
for ( let i in salaries) {

    // add a currency symbol
    let salary = "$" + salaries[i];

    // display the values
    console.log(`${i} : ${salary}`);
}

Output:

Jack : $24000,
Paul : $34000,
Monica : $55000

The for…in loop is used in the preceding example to iterate over the salary object’s properties. The string $ is then appended to each value of the object.

for…in with Strings

To iterate over string values, you can also use a for…in loop. As an example:

const string = 'code';

// using for...in loop
for (let i in string) {
    console.log(string[i]);
}

Output:

c
o
d
e

for…in with Arrays

You can also use for…in with arrays. For example:

// define array
const arr = [ 'hello', 1, 'JavaScript' ];

// using for...in loop
for (let x in arr) {
    console.log(arr[x]);
}

Output:

hello
1
JavaScript

Note: It is important to note that you should not use for…in to iterate over an array where the index order is important.

You may like:

while and do-while loop in JavaScript

Leave a Reply