Arrays and iterables

An array in JavaScript is a type of object that is specialized in that it contains a set of ordered elements.

You can express an array using its literal syntax, which is a comma-separated list of expressions delimited by square brackets:

const friends = ['Rachel', 'Monica', 'Ross', 'Joe', 'Phoebe', 'Chandler'];

These comma-separated expressions can be as complex or simple as we desire:

[
[1, 2, 3],
function() {},
Symbol(),
{
title: 'wow',
foo: function() {}
}
]

An array is capable of containing all manner of values. There are very few constraints on how we can use arrays. Technically, an array's limited to a length of around 4 billion, due to its length being stored as a 32-bit integer. For most purposes, of course, this should be absolutely fine. 

Arrays have a numeric property for every indexed element within them and a length property to describe how many elements there are. They also have a set of useful methods for reading from and operating on the data within them:

friends[0]; // => "Rachel"
friends[5]; // => "Chandler"
friends.length; // => 6

friends.map(name => name.toUpperCase());
// => ["RACHEL", "MONICA", "ROSS", "JOE", "PHOEBE", "CHANDLER"]

friends.join(' and ');
// => "Rachel and Monica and Ross and Joe and Phoebe and Chandler"

Historically, arrays were iterated over using conventional for(...) and while(...) loops that increment a counter toward the length so that, upon each iteration, the current element could be accessed via array[counter], like so:

for (let i = 0; i < friends.length; i++) {
// Do something with `friends[i]`
}

Nowadays, however, it's preferable to use other methods of iteration, such as forEach or for...of:

for (let friend of friends) {
// Do something with `friend`
}

friends.forEach((friend, index) => {
// Do something with `friend`
});

for...of has the benefit of being breakable, meaning you can use break and continue statements within them and easily escape from the iteration.  It will also work on any object that is iterable, whereas forEach is only an Array method. The forEach style, however, is useful in that it provides you with the current index of the iteration via the second argument to your callback.

Which style of iteration you use should be determined by the value you are iterating over and what you wish to do on each iteration. Nowadays, it is quite rare to need to use traditional styles of array iteration such as for(...) and while(...).
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset