This section covers arrays which are handy objects for containing collections of ordered data. Arrays are an ordered list of data, each having an index number. The numbers start at 0, meaning that arrays are zero indexed, and go all the way to the length of the array minus one. There are tons of useful array methods, from ones that perform an action on each item in the array, to ones that transform the array, such as the sort function. The array is one of the most basic data structures and are used all the time.
When shouldn’t I use arrays?
Arrays come with some limitations. For instance, when you remove the first item from an array then every other item in the array has to have it’s index decremented by one. For small arrays this is negligible, but for arrays of non trivial sizes this can slow down your program to a stand still, especially if it’s done many times over. So if you’re working with a data set of non-trivial size, make sure you think about how much you’re moving items on your array around.
Section 4: Arrays
4.1: Use the literal syntax for array creation. eslint: no-array-constructor
There are two main ways of creating arrays. Just like with object construction, using literals is faster and less prone to errors and is therefore the preferred method for creating arrays.
4.3: Use array spreads … to copy arrays.
4.4: To convert an array-like object to an array, use
Once again, the preferred method is more expressive and easier to write.
const foo = document.querySelectorAll('.foo'); const nodes = Array.from(foo);
4.6: Use return statements in array method callbacks. It’s ok to omit the return if the function body consists of a single statement returning an expression without side effects, following 8.2. eslint: array-callback-return
There are certain methods that execute a block of code on each item in an array (Ex. reduce, map, filter, etc.). That block of code is referred to as a callback. If the callback is more than one line long, use a return statement. Otherwise skip it.
Why Should I Care?
Next up: Destructuring
Next Saturday I’ll explain what destructuring is and why it’s useful.