0

I was learning about Object.entries in Javascript and I came across the following code snippet:

const object1 = {
  a: 'somestring',
  b: 42
};

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}

// expected output:
// "a: somestring"
// "b: 42"

we can see that there is a "of " keyword used in here; can anyone tell me how it works?

for (const [key, value]  of Object.entries(object1)) {
Yousaf
  • 27,861
  • 6
  • 44
  • 69

2 Answers2

1

The of keyword is usually used to iterate through iterable objects (in this example you have given, is the object of Object.entries).

For more explanations and examples, you can find out from this documentation by Mozilla.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

Edited according to VLAZ comment: There is no of keyword nor is it a standalone thing. It's only a part of for..of and for await..of statements.

CodeName
  • 559
  • 2
  • 6
  • 23
  • 1
    "*The of keyword is usually used to iterate through iterable objects*" 1. There is no `of` keyword. It's not a standalone thing. It's *only* a part of `for..of` and `for await..of` statements. 2. "usually" implies there are some unusual cases where `for..of` is not used with iterables. Yet, that is its only purpose - It's not possible to use `for..of` with anything that's not iterable. – VLAZ Jun 28 '22 at 06:06
  • @VLAZ edited according to your comments. thanks for the insight. – CodeName Jun 28 '22 at 08:21
0

The for...of loop, which iterates over property values, is a feature added to the JavaScript specification in ECMAScript 2015.

Please look at this post:

JavaScript `of` Keyword (for...of loops)