JavaScript For In
- Previous Page JS Loop For
- Next Page JS Loop For Of
For In Loop
JavaScript for in
The statement loops over the properties of the object:
Syntax
for (key in object) { // code block to be executed }
Example
const person = {fname:"Bill", lname:"Gates", age:25}; let text = ""; for (let x in person) { text += person[x]; }
Example Explanation
- for in Loop Traversal person Object
- Returns an object each time iterationKey (x)
- The key is used to access theValue
- The value of the key is person[x]
For In Traversal of Array
JavaScript for in
The statement can also iterate 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]; }
If the indexOrderIt is very important, please do not use for in.
The index order depends on the implementation and may not access the array values in the order you expect.
It is best to use when the order is important for Loop,for of Loop or Array.forEach().
Array.forEach()
forEach()
The method calls the function once for each array element (callback function).
Example
const numbers = [45, 4, 9, 16, 25]; let txt = ""; numbers.forEach(myFunction); function myFunction(value, index, array) { txt += value; }
Please note that this function takes 3 parameters:
- Item value
- Item index
- Array itself
The example above uses only the value parameter. It can be rewritten as:
Example
const numbers = [45, 4, 9, 16, 25]; let txt = ""; numbers.forEach(myFunction); function myFunction(value) { txt += value; }
- Previous Page JS Loop For
- Next Page JS Loop For Of