The for...instatement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.
(… and arrays are "special objects")
constspecial=Symbol('special');constgrades=[];grades.a=1;grades[0]=80;grades.c=3;grades[1]=85;grades.b=2;grades[2]=90;grades[special]=42;console.log(grades[special]);console.log(grades.hasOwnProperty('1'));// as a stringconsole.log(grades.hasOwnProperty(1));// as a numberconsole.log(grades.hasOwnProperty(special));// as a symbolfor(constkeyingrades){console.log(`${keyToString(key)}: ${grades[key]}`);}functionkeyToString(key){switch(typeofkey){case'symbol':return'some symbol';case'string':return`'${key}'`;}returnkey.toString();}console.log('Just keys()');for(constkeyofgrades.keys()){console.log(`${keyToString(key)}: ${grades[key]}`);}/*
42
true
true
true
"'0': 80"
"'1': 85"
"'2': 90"
"'a': 1"
"'c': 3"
"'b': 2"
"Just keys()"
"0: 80"
"1: 85"
"2: 90"
Note how 'in' always produces "string"s
While '.keys()' used with 'of' actually returns "number"s
*/
As the reference linked to states:
The for...ofstatement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.
Being an array method
.forEach()
is really the only one that is limited to arrays.Note that eslint no-constant-condition won't tolerate
while(true)
but will acceptfor(;;)
.As the reference linked to states:
(… and arrays are "special objects")
As the reference linked to states:
Bonus: Both
for...in
and.forEach()
will skip "holes" ("empty values") in arrays whilefor...of
, .keys() and .entries() will not.Thank you so much for shedding some light!