JS loops (forEach, for...in, for...of)
By xyz on 2 weeks ago|0 comment||
0
The best use for these loops is as follows:
Array: use for...of (or forEach)
Object: use for...in
if you work with arrays and need access to indexes, use for and forEach
I remember this as A ray of sunshine and foreign objects in the sky, which reminds me that:
Array -> for...of
Object -> for...in
// for... in loop
let person = {name: "SpongeBob", lastName: "SquarePants", age: 34}
for (let property in person) {
console.log(`${property}: ${person[property]}`);
}
// RESULT:
// "name: SpongeBob"
// "lastName: SquarePants"
// "age: 34"
let students = ["SpongeBob", "Patrick"]
for (let element in students){
console.log(`${element} is ${students[element]}`)
}
// RESULTS
// "0 is SpongeBob"
// "1 is Patrick"
// "name is Mr. Krabs"
// for... of loop
const array = [1, 2, 3, 4];
for (const item of array) {
console.log(item);
}
// RESULTS
// 1
// 2
// 3
// 4
// forEach
array.forEach(function(currentValue, index, arr))
let students = ['John', 'Sara', 'Jack'];
students.forEach(() => item, index, arr) {
arr[index] = 'Hello ' + item;
});
console.log(students);
// ["Hello John", "Hello Sara", "Hello Jack"]
Add a Comment
Comments
Comments MIA, jokes needed ASAP. Add yours! 😄