By Hemanta Sundaray on 2021-06-02
A for loop repeats until a specified condition evaluates to false.
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
The for...each method executes a provided function once for each array element.
// 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 ]
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.
for (variable in object) {
statement
}
const object = {
firstName: "Hemanta",
lastName: "Sundaray",
}
for (key in object) {
console.log(`${object[key]}`)
}
// output
Hemanta
Sundaray
Used to loop over iterable objects. (Arrays, strings, Maps, Sets etc.).
for (variable of iterable) {
statement
}
const numbers = [10, 20, 30]
for (const number of numbers) {
console.log(number * 2)
}
//outout
20
40
50
const lastName = "sundaray"
let fullName = "Hemanta "
for (letter of lastName) {
fullName += letter
}
console.log(fullName)
//output
Hemanta Sundaray