Member-only story
What is for — in Loop in JavaScript?
Learn what is for — in loop in JavaScript and how to use for — in loop in JavaScript with examples.
For — in Loop
In JavaScript, there are 3 different for
loops can be used to iterate over iterable variables.
For — in loop is used for iterating over the keys of the iterable. That means we can directly access the key value as iterable.
Let’s see what is the syntax for — in loop in JavaScript:
for (key in iterable) {
// body of for...in
}
In this example above we have defined a key, and that variable is assigned to key elements of the iterable like arrays, string, map, set, etc.
When you get the key of the iterable you can directly access its value.
For — in Loop with Objects
Objects can be used in for — in loops. Let’s look at the example usage:
// Object
const priceList = {
food1: 10,
food2: 12,
drink1: 2,
drink1: 3
}// using for...in
for ( let key in priceList ) {