JavaScript Loop For In
JavaScript Basics

JavaScript Loop For In

The For In Loop

The JavaScript for in statement loops through the properties of an object.

Syntax

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

Example

Example Explained

  • The for in loop iterates over the car object.
  • Each iteration returns a property key (prop).
  • The key is used to access the corresponding value (car[prop]).

For In Over Arrays

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

Syntax

javascriptCopy code

for (variable in array) {
 // code block to be executed
}

Example

javascriptCopy code

const fruits = ["Apple", "Banana", "Cherry"];

let list = "";
for (let index in fruits) {
 list += fruits[index] + " ";
}

Note

Do not use for in over an array if the index order is important. The index order is implementation-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

javascriptCopy code

const numbers = [1, 2, 3, 4, 5];

let result = "";
numbers.forEach(addNumber);

function addNumber(value) {
 result += value + " ";
}

Note

The function passed to forEach() takes three arguments:

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

The example above uses only the value parameter.

Revised Example

javascriptCopy code

const numbers = [10, 20, 30, 40, 50];

let sum = 0;
numbers.forEach(calculateSum);

function calculateSum(value) {
 sum += value;
}

This revised example calculates the sum of the numbers in the array.

Summary

  • Use for in to loop through the properties of an object.
  • Use for in with caution on arrays, as the order may not be guaranteed.
  • Prefer for, for of, or Array.forEach() when the order of elements in an array is important.

Take a look into your desired course