How to use for…in loop in Javascript ?
The for...in
loop is used to iterate through the keys of an object. Syntax of JavaScript for…in Loop
for (key in object) {
// body of for...in
};
Here object – The object whose keys we want to iterate over and key – A variable that stores a single key belonging to object.
const employee = {
name: "John",
class: 8
};
// loop through the keys of student object
for (let key in employee) {
// display the key-value pairs
console.log(`${key} => ${employee[key]}`);
};
// Output:
// name => John
// class => 8
You can use for...in
to iterate over an iterable such arrays and strings but you should avoid using for...in
for iterables.