Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Loop For In

The For In Loop

The JavaScript for/in statement iterates over the properties of an object.

Syntax

for (key in object) {
  // code block to be executed
}

Example

const person = {fname:“John”, lname:“Doe”, age:25};

let text = “”;
for (let x in person) {
  text += person[x];
}

Example Explained

  • The for/in loop iterates over a person object.
  • In each iteration, it returns a key (x), which is then used to access the corresponding value.
  • The value can be accessed using person[x].

For In Over Arrays

The JavaScript for/in statement can also iterate over the properties of an array.

Syntax

for (variable in array) {
  code
}

Example

const numbers = [45491625];

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.

Array.forEach()

The forEach() method invokes a callback function once for each element in the array.

Example

const numbers = [45491625];

let txt = “”;
numbers.forEach(myFunction);

function myFunction(value, index, array) {
  txt += value;
}

Note that the function accepts three arguments:

  • The item value
  • The item index
  • The array itself

The example above uses only the value parameter and can be rewritten to include the others:

Example

const numbers = [45491625];

let txt = “”;
numbers.forEach(myFunction);

function myFunction(value) {
  txt += value;
}