The JavaScript for/in statement iterates over the properties of an object.
for (key in object) { // code block to be executed } |
const person = {fname:“John”, lname:“Doe”, age:25}; let text = “”; for (let x in person) { text += person[x]; } |
The JavaScript for/in statement can also iterate over the properties of an array.
for (variable in array) { code } |
const numbers = [45, 4, 9, 16, 25]; let txt = “”; for (let x in numbers) { txt += numbers[x]; } |
Avoid using for/in with an array if the index order matters. The index order is implementation-dependent, and array values may not be accessed in the expected sequence. It’s better to use a for loop, a for/of loop, or Array.forEach() when maintaining order is important. |
The forEach() method invokes a callback function once for each element in the array.
const numbers = [45, 4, 9, 16, 25]; let txt = “”; numbers.forEach(myFunction); function myFunction(value, index, array) { txt += value; } |
Note that the function accepts three arguments:
The example above uses only the value parameter and can be rewritten to include the others:
const numbers = [45, 4, 9, 16, 25]; let txt = “”; numbers.forEach(myFunction); function myFunction(value) { txt += value; } |