JavaScript Code


JavaScript for…in Loop


for…in loop

for (key in object) {
  //code
}
  • for is keyword.
  • key is variable to hold the current key of object during iteration.
  • object is any valid object that has keys and respective values.
  • code is any valid JavaScript code.

for…in loop iterates over the keys of the object, and executes the block of code for each key.

we can also use for…in loop to iterate over the elements of an array. index of the elements would be key, and the element would be the value.

Examples

1. for…in loop to print the key-value pairs of student object.

const student = {
    name: 'Anita',
    class: 5,
    age: 11,
    nationality: 'India'
}

for ( let key in student ) {
    console.log(key + " - " + student[key]);
}

2. for…in loop to iterate over elements of an array.

let fruits = [ 'apple', 'banana', 'cherry' ]

for ( let index in fruits ) {
    console.log(index + ' - ' + fruits[index]);
}