Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between iterable and enumerable in JS? I am going through For/of and For/In loop and these terms are coming up frequently

I am coming across terms Iterable and Enumerable while studying For/in and For/of loops. Objects are supposed be enumerable and we have to use For/in loop to loop over the properties of the object and For/of to loop over the arrays and strings. I am unable to wrap my head around these two terms. What is the difference between these two?

like image 712
Mahwash Avatar asked Mar 02 '23 12:03

Mahwash


1 Answers

There are a few things that stand out one from another.

A bit about Iterable:

  • Iterable objects are a generalization of arrays. That's a concept that allows us to make any object useable in a for..of the loop;
  • The iterable is an interface that specifies that an object can be accessible if it implements a method who is key is [symbol.iterator] link.

A bit about Enumerable:

  • It simply means that the property will show up if you iterate over the object using for..in loop or Object.keys;
  • An enumerable property in JavaScript means that a property can be viewed if it is iterated using the for…in loop or Object.keys() method. All the properties which are created by simple assignment or property initializer are enumerable by default.
  1. Enumerable [for in] looking at the properties that are inside of the object, not the values [only where enumerable: true - by default for all props];
  2. Iterable [for of] looking at the values;

A bit more in-depth:

Iterator is another object that is attached to the array, and it tells other function how to access all the different values inside of it. there are array, string, NodeList, Sets, Maps they have built-in iterators, but the object does not have it.

The object is not iterable by default, but you can implement it.

So you can use

  • for .. of for [array, Map, Set, String] to iterate over values;
  • for .. in for an array to iterate over a key;
  • for .. in for objects to enumerate its (object's) properties;
  • looping over NodeList.

Please, take a look at the example either here or using a provided link for a sandbox. Sandbox link for the same example.

let arr = ['value1', 'value2', 'value3'];

let obj = {
  propName1: 'propValue1',
  propName2: 'propValue2',
  propName3: 'propValue3'
};

console.log('=====================WORKING WITH ARRAYS===================');
console.log('For Of ')
for (const value of arr) {
  console.log('value: ', value);
}

console.log('For In');
for (const key in arr) {
  console.log('key: ', key, ' value: ', arr[key]);
}

console.log('=====================WORKING WITH OBJECTS===================');
console.log('For In:');
for (const prop in obj) {
  console.log('prop: ', prop, 'value: ', obj[prop]);
}

Object.defineProperty(obj, "definedPropEnFalse", {
  value: 'value of definedPropEnFalse',
  enumerable: false,
});

Object.defineProperty(obj, "definedPropEnTrue", {
  value: 'value of definedPropEnTrue',
  enumerable: true,
});

console.log('For In for Objects with enumerables:');
for (const prop in obj) {
  console.log('prop: ', prop, 'value: ', obj[prop]);
}

console.log('For In for Objects with Object.keys and forEach:');
Object.keys(obj).forEach(e => console.log(`key=${e}  value=${obj[e]}`));


console.log('=====================WORKING WITH STRINGS===================');
let str = "Go Over A String"
console.log('Using For Of for String:');
for (const char of str) {
  console.log(char);
}


console.log('=====================WORKING WITH Sets===================');
console.log("Looping over a Set");
let testSet = new Set();
testSet.add('Hello');
testSet.add('Hope');
testSet.add('You are getting it xD');

for (const setItem of testSet) {
  console.log(setItem);
}


console.log('=====================WORKING WITH Maps===================');
console.log('Iterate over Map using For of')
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");

for (const [key, value] of myMap.entries()) {
  console.log(key, value);
}

You may ask how should I remember it? - Easy!

A mnemonic:

  • 'o'f -> not 'o'bjects;
  • 'i'n -> not 'i'terables.

Another mnemonic:

  • for..in..keys === foreign keys === use for...in for keys;
  • for...of for values.

in gives you index.

Taken from this post's comment


If an object isn’t technically an array but represents a collection (list, set) of something, then for..of is a great syntax to loop over it.

like image 149
Utmost Creator Avatar answered Apr 30 '23 05:04

Utmost Creator