For Loops in JavaScript

By Hemanta Sundaray on 2021-06-02

for

A for loop repeats until a specified condition evaluates to false.

Syntax

for ([initialization]; [condition]; [final-expression]) {
    statement
}

Initialization: Typically used to initialize a counter variable.

Condition: An expression to be evaluated before each loop iteration.

Final-expression: Generally used to increment the counter variable.

for (let i = 0; i < 5; i++) {
  console.log(i)
}
// output
0
1
2
3
4

for...each

The for...each method executes a provided function once for each array element.

Syntax

// Arrow function

forEach((element) => { ... } )

forEach((element, index) => { ... } )

forEach((element, index, array) => { ... } )

element: The current element being processed in the array

index(optional): The index of the element in the array.

array(optional): The array for...each was called upon.

const team = ["Sam", "Alex", "Cathy"]

team.forEach(teamMember => console.log(`Hello ${teamMember}`))
// output

Hello Sam
Hello Alex
Hello Cathy
const nums = ["10", "20", "30"]

nums.forEach((num, index, arr) => (arr[index] = num * 2))

console.log(nums)
// output

[ 20, 40, 60 ]

for...in

Used to loop through the properties of an object.(It iterates through the properties in an arbitrary order.)

Don’t use for...in loop to iterate over an Array where the index order is important.

Syntax

for (variable in object) {
   statement
}
const object = {
  firstName: "Hemanta",
  lastName: "Sundaray",
}

for (key in object) {
  console.log(`${object[key]}`)
}
// output

Hemanta
Sundaray

for...of

Used to loop over iterable objects. (Arrays, strings, Maps, Sets etc.).

Syntax

for (variable of iterable) {
   statement
}

Iterating over an array

const numbers = [10, 20, 30]

for (const number of numbers) {
  console.log(number * 2)
}
//outout

20
40
50

Iterating over a string

const lastName = "sundaray"

let fullName = "Hemanta "

for (letter of lastName) {
  fullName += letter
}

console.log(fullName)
//output

Hemanta Sundaray

Join the Newsletter