JavaScript For In
The For In Loop
The for...in loop iterates over the enumerable properties of an object.
The for...in loop is primarily used for objects to access their property names (keys).
Syntax
for (key in object) {
// code block to be executed
}
- key
A variable that holds the name (key) of each property during the iterations - object
The object whose properties are being iterated over
A JavaScript for in
statement loops through the properties
of a person object:
Example
const person = {fname:"John", lname:"Doe", age:25};
let text = "";
for (let x in person) {
text += person[x];
}
Try it Yourself »
Example Explained
- The for in loop iterates over a person object
- Each iteration returns an x (a key)
- The x is used to access the value of x
- The value of x is person[x]
For In Over Arrays
The JavaScript for in
statement can also loop over the properties of an Array:
Syntax
for (variable in array) {
code
}
Example
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x];
}
Try it Yourself »
Control Flow
Like in other JavaScrpt loops, you can use control flow statements inside the loop:
break
break the loop execution and go to the statements after the loopcontinue
break the loop execution and go to the next iteration of the loop
Enumerable Properties
The for...in
loop only iterates over enumerable properties.
Properties with the enumerable attribute is set to false,
like some built-in methods or properties defined with
Object.defineProperty()
will not be included.
The Prototype Chain
The for...in
loop also iterates over enumerable properties
inherited from the object's prototype chain.
To avoid this, you can use hasOwnProperty()
inside the loop
to check if the property belongs directly to the object itself.
Note
Do not use for in over an Array if the index order is important.
The index order is engine-dependent, and array values may not be accessed in the order you expect.
It is better to use a for loop, a for of loop, or Array.forEach() when the order is important.
Array.forEach()
The forEach()
method calls a function (a callback function) once for each array element.
Example
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value, index, array) {
txt += value;
}
Try it Yourself »
Note that the function takes 3 arguments:
- The item value
- The item index
- The array itself
The example above uses only the value parameter. It can be rewritten to:
Example
const numbers = [45, 4, 9, 16, 25];
let txt = "";
numbers.forEach(myFunction);
function myFunction(value) {
txt += value;
}
Try it Yourself »