Using a loop is almost a must in our day to day life. But have you ever thought what kind of loop should you use? Do you know the difference between enumerables and iterables? This article sheds some light in this space, so read on if youβre interested.
Looping has seen quite a few changes from when I started programming. I remember using while loops and thinking wow, this is cool (I was printing starts on console using MS-DOS).
For loop is another way to iterate through a data structure which contains many items. But non of these methods iterate over the actual structure. They use a sequence, usually named i
which mirrors the identifier for you.
const fruits = ['π', 'π', 'π'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// π, π, π
Here i
is an index which allows you to access the elements of fruits array and is not part of the array itself. But with progress on JavaScript towards more modern ways of programming, things have changes now. We have for...in
, and for...of
loops which use a different mechanism for going through items in a collection.
Before we delve into these newer ways of iteration, we need to be on the same page around some concepts. So letβs go through them now:
That didnβt click for me at first, but after going through some examples, it finally made sense. If you consider a full pencil case, thatβs an enumerable. When you line up at Aldi to pay, that line is an iterable. A wad of cash is an enumerable, whereas a row of keys on your keyboard is an iterable.
π‘ In order for an object to be
iterable
, it MUST implement an@@iterator
property which returns an iterator. An iterator object is one which has anext
method which returns the next item in the collection. Thatβs why an object is not an iterable.
By now you should have started to see the pattern here. The best analogy I came across is:
π Enumerables are like rectangles whereas iterables are squares. This means all
iterables
areenumerables
, however, not allenumerables
areiterables
.
for...in
So letβs start from enumerables
. You can go through enumerables using for...in
. The use case is mainly to go through key-value pairs in an object:
const superCar = {
make: 'Lamborghini',
model: 'Veneno',
year: '2020'
};
for (let key in superCar) {
console.log(`${key} --> ${superCar[key]}`);
}
// make --> Lamborghini
// model --> Veneno
// year --> 2020
You can also use for...in
to go through index values of an iterable like an array or a string:
let fact = 'Lamborghini is the best!';
for (let index in fact) {
console.log(`Index of ${fact[index]}: ${index}`);
}
// Index of L: 0
// Index of a: 1
// Index of m: 2
// Index of b: 3
// ...
π‘ Beware that you canβt iterate on
Symbol
properties withfor...in
and thatβs becauseSymbols
are primitive data types that are always unique. They are generally used as private properties to avoid name clashes when inheritance is used.
for...of
This kind of loop is applicable to βiterable objectsβ meaning the item after of
MUST be an iterable
:
const fruits = ['π', 'π', 'π'];
for (let fruit of fruits) {
console.log(`${fruit} is delicious.`);
}
// π is delicious.
// π is delicious.
// π is delicious.
And again we can use it on strings, but with a slight difference:
let fact = 'Yas';
for (let char of fact) {
console.log(char);
}
// Y
// a
// s
We saw the difference between these two modern ways of looping through collections, letβs make more informed decisions as to use what where and write cleaner, more readable code ππ½.