JS Tricks

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! 😄

What is JavaScript Hacks? 🚀

Hey there, fellow code adventurer! Ever wished JavaScript could be more than just lines of serious code? Well, welcome to JS Hacks – where JavaScript gets a playful makeover! 🎉

So, whether you're a coding newbie or a seasoned pro, join us on this epic quest to discover the quirkiest, coolest, and downright silliest JavaScript hacks out there. Trust us, your code will thank you (and maybe even crack a smile). 😄

Ready to hack, slash, and LOL your way through JavaScript? Let's dive in and unleash the fun-tastic power of JS Hacks together! 💻✨


DISCOVER

ENGAGE

Add Trick