JavaScript Loops - For in - Part 3

Published on
2 mins read
––– views

Another day, another JavaScript loop to learn. What if we want to loop over properties of an object? Let me introduce you *drum roll* the for in loop.

On this post, I won't go over what are objects in JavaScript because I already explained them in Part 2 of this series. You can check them below

[If you want to learn for loop, here is the part 1] --- Link after build

[If you want to learn forEach loop and objects, here is the part 2] --- Link after build

What is for in loop?

For in loop is similar to forEach, which talked about on the last post. We use to loop over properties of an object. The main difference is forEach cannot loop an object directly. If you place the object inside an array, it can. for in can loop over an object even if it isn't inside an array.

For in loops can loop over objects

For in loops CAN NOT loop over objects inside an array.

forEach loops can loop over arrays.

forEach loops cannot loop over objects that AREN'T inside an array


examples:

forEach

let person = { name: 'Dude', age: 30, job: 'Being awesome' }

// THIS CODE WILL THROW AN ERROR
person.forEach(function (person) {
  console.log(person)
})

// to loop the person, we would need to wrap that inside an array.

let person = [{ name: 'John', age: 30, job: 'teacher' }]

// AFTER PLACING IT INSIDE [ ], CODE WILL RUN
person.forEach(function (person) {
  console.log(person)
})

for in

let person = [{ name: 'John', age: 30, job: 'teacher' }]
/// THIS CODE WOULD RETURN [Object Object], not useful.
for (let property in person) {
  console.log(property + ': ' + person[property])
}

// This will run //
let person = { name: 'John', age: 30, job: 'teacher' }
for (let property in person) {
  console.log(property + ': ' + person[property])
}
/* returns this:
"name: John"
"age: 30"
"job: teacher"
*/