DEV Community

Jordi
Jordi

Posted on • Originally published at jordienric.com

6 2

Learn JavaScript's for...of and for...in - in 2 minutes

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) {
    console.log(propertyKey)
}

// Will result in:
> 'keyOne'
> 'keyTwo'
> 'keyThree'
Enter fullscreen mode Exit fullscreen mode

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) {
    console.log(myObject[propertyKey])
}
Enter fullscreen mode Exit fullscreen mode

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) {
    console.log(myValue)
}

// Will result in
> 'valueOne'
> 'valueTwo'
> 'valueThree'
Enter fullscreen mode Exit fullscreen mode

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (1)

Collapse
 
leoloopy profile image
Leo

Nice article, short and precise

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay