#frontend 2021, 04, 20

Do you know the difference between for...in and for...of in Javascript?

The for...in loop

We use for...in when we want to use the keys of an Object.

const myObject = {
  keyOne: 'valueOne',
  keyTwo: 'valueTwo',
  keyThree: 'valueThree'

for (const propertyKey in myObject) {

// Will result in:
> 'keyOne'
> 'keyTwo'
> 'keyThree'

As we can see in the example propertyKey will be the key of the object.

You should know 💡 for...in will ignore any Symbols in your Object

If we want to access the value we can still do it like this

for (const propertyKey in myObject) {

But instead of doing this we could use a for...of loop.

The for...of loop

The for...of loop will iterate over the values of the Iterable Object.

Here's an example with an Array

const myIterableObject = [
  'valueOne', 'valueTwo', 'valueThree'

for (const myValue of myIterableObject) {

// Will result in
> 'valueOne'
> 'valueTwo'
> 'valueThree'

This is a good alternative to the forEach method

This was a quick introduction to these two syntaxes of the for loop in Javascript. I recommend you play around with them. These two are really useful to know when you want to write short for loops.

🚀 Follow me on twitter for more