JavaScript for...in loop

JavaScript for...in loop

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

In the previous tutorials, we have covered:

There are also other types of loops. The for..in loop in JavaScript allows you to iterate over all property keys of an object.


JavaScript for...in loop

The syntax of the for...in loop is:

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

In each iteration of the loop, a key is assigned to the key variable. The loop continues for all object properties.

Note: Once you get keys, you can easily find its value.


Example 1: Iterate through an object

let 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

In the above program, the for...in loop is used to iterate over the student object and print all its properties.

  • The object key is assigned to the variable i.
  • student[i] is used to access the value of i.

Example 2: Update Values of Properties

let 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

In the above example, the for...in loop is used to iterate over the properties of the numbers object. Then, the string $ is added to each value of the object.


for...in with Strings

You can also use for...in loop to iterate over the string values. For example,

let 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
let arr = [ 'hello', 1, 'JavaScript' ];

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

Output

hello
1
JavaScript

You will learn more about the arrays in the later tutorials.

Note: You should not use for...in to iterate over an array where the index order is important.

One of the better ways to iterate over an array is using the for...of loop.

To learn more about the for...of loop, visit JavaScript for...of loop.