for…in loop
for (key in object) {
//code
}
for
is keywordkey
is variable to hold the current key of object during iterationobject
is any valid object that has keys and respective valuescode
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]);
}