31 Arrays ('Array') - JavaScript For Impatient Programmers (ES2022 Edition)
31 Arrays ('Array') - JavaScript For Impatient Programmers (ES2022 Edition)
31 Arrays (Array)
https://exploringjs.com/impatient-js/ch_arrays.html 1/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
JavaScript Arrays are a very flexible data structure and used as lists, stacks, queues, tuples
(e.g. pairs), and more.
// Creating an Array
const arr = ['a', 'b', 'c']; // Array literal
assert.deepEqual(
https://exploringjs.com/impatient-js/ch_arrays.html 2/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
arr,
[ // Array literal
'a',
'b',
'c', // trailing commas are ignored
]
);
// Reading elements
assert.equal(
arr[0], 'a' // negative indices don’t work
);
assert.equal(
arr.at(-1), 'c' // negative indices work
);
// Writing an element
arr[0] = 'x';
assert.deepEqual(
arr, ['x', 'b', 'c']
);
https://exploringjs.com/impatient-js/ch_arrays.html 3/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
);
// Output:
// 'a'
// 'b'
// 'c'
https://exploringjs.com/impatient-js/ch_arrays.html 4/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
// Output:
// 0, 'a'
// 1, 'b'
// 2, 'c'
Creating and filling Arrays when we can’t use Array literals (e.g. because we don’t know
their lengths in advance or they are too large):
const four = 4;
// A range of integers
assert.deepEqual(
Array.from({length: four}, (_, i) => i),
[0, 1, 2, 3]
);
https://exploringjs.com/impatient-js/ch_arrays.html 5/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
This section gives a brief overview of the Array API. There is a more comprehensive quick
reference at the end of this chapter.
> ['■','●','▲'].slice(1, 3)
['●','▲']
> ['■','●','■'].filter(x => x==='■')
['■','■']
> ['■','●','▲'].join('-')
'■-●-▲'
https://exploringjs.com/impatient-js/ch_arrays.html 6/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
> ['■','●','■'].includes('■')
true
> ['■','●','■'].indexOf('■')
0
https://exploringjs.com/impatient-js/ch_arrays.html 7/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
> ['■','●','■'].lastIndexOf('■')
2
> ['■','●','■'].find(x => x==='■')
'■'
> ['■','●','■'].findIndex(x => x==='■')
0
Fixed-layout Arrays: Used this way, Arrays have a fixed number of indexed
elements. Each of those elements can have a different type.
Sequence Arrays: Used this way, Arrays have a variable number of indexed
elements. Each of those elements has the same type.
Notably, sequence Arrays are so flexible that we can use them as (traditional) arrays,
stacks, and queues. We’ll see how later.
https://exploringjs.com/impatient-js/ch_arrays.html 8/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
The Array literal starts and ends with square brackets []. It creates an Array with three
elements: 'a', 'b', and 'c'.
const arr = [
'a',
'b',
'c',
];
To read an Array element, we put an index in square brackets (indices start at zero):
The range of Array indices is 32 bits (excluding the maximum length): [0, 232−1)
Every Array has a property .length that can be used to both read and change(!) the
number of elements in an Array.
https://exploringjs.com/impatient-js/ch_arrays.html 9/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
Another way of (destructively) appending an element is via the Array method .push():
> arr.push('d');
> arr
[ 'a', 'b', 'c', 'd' ]
> arr.length = 1;
> arr
[ 'a' ]
exercises/arrays/remove_empty_lines_push_test.mjs
Several Array methods support negative indices. If an index is negative, it is added to the
length of an Array to produce a usable index. Therefore, the following two invocations of
.slice() are equivalent: They both copy arr starting at the last element.
The Array method .at() returns the element at a given index. It supports positive and
negative indices (-1 refers to the last element, -2 refers to the second-last element, etc.):
https://exploringjs.com/impatient-js/ch_arrays.html 10/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
In contrast, the bracket operator [] does not support negative indices (and can’t be
changed because that would break existing code). It interprets them as keys of non-
element properties:
assert.equal(
arr[-1], 'non-element property'
);
or we can assign a new empty Array to the variable storing the Array:
The latter approach has the advantage of not affecting other locations that point to the
same Array. If, however, we do want to reset a shared Array for everyone, then we need
the former approach.
Inside an Array literal, a spread element consists of three dots (...) followed by an
expression. It results in the expression being evaluated and then iterated over. Each
iterated value becomes an additional Array element – for example:
That means that we can use spreading to create a copy of an Array and to convert an
iterable to an Array:
However, for both previous use cases, I find Array.from() more self-descriptive and prefer
it:
assert.deepEqual(
Array.from(original.keys()), [0, 1, 2]
);
Spreading is also convenient for concatenating Arrays (and other iterables) into Arrays:
Copying Arrays via spreading or via Array.from() is shallow: We get new entries in a
new Array, but the values are shared with the original Array. The consequences of
https://exploringjs.com/impatient-js/ch_arrays.html 12/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
shallow copying are demonstrated in §28.4 “Spreading into object literals (...)
[ES2018]”.
Listing Array indices is different from listing properties. The former produces numbers;
the latter produces stringified numbers (in addition to non-index property keys):
assert.deepEqual(
Object.keys(arr),
['0', '1', 'prop']);
instanceof is usually fine. We need Array.isArray() if a value may come from another
realm. Roughly, a realm is an instance of JavaScript’s global scope. Some realms are
isolated from each other (e.g., Web Workers in browsers), but there are also realms
between which we can move data – for example, same-origin iframes in browsers. x
https://exploringjs.com/impatient-js/ch_arrays.html 13/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
instanceof Arraychecks the prototype chain of x and therefore returns false if x is an Array
from another realm.
> typeof []
'object'
We have already encountered the for-of loop earlier in this book. This section briefly
recaps how to use it for Arrays.
The following for-of loop iterates over [index, element] pairs. Destructuring (described
later), gives us convenient syntax for setting up index and element in the head of for-of.
https://exploringjs.com/impatient-js/ch_arrays.html 14/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
// Output:
// 0, 'a'
// 1, 'b'
Some operations that work with Arrays require only the bare minimum: values must only
be Array-like. An Array-like value is an object with the following properties:
For example, Array.from() accepts Array-like objects and converts them to Arrays:
assert.deepEqual(
Array.from({length:2, 0:'a', 1:'b'}),
[ 'a', 'b' ]);
interface ArrayLike<T> {
length: number;
[n: number]: T;
}
Array-like objects used to be common before ES6; now we don’t see them very often.
There are two common ways of converting iterables and Array-like values to Arrays:
Inside an Array literal, spreading via ... converts any iterable object into a series of Array
elements. For example:
https://exploringjs.com/impatient-js/ch_arrays.html 16/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
.from<T, U>(
iterable: Iterable<T> | ArrayLike<T>,
mapFunc: (v: T, i: number) => U,
thisArg?: any)
: U[]
In other words: we are going from an iterable with elements of type T to an Array with
elements of type U.
This is an example:
The best way of creating an Array is via an Array literal. However, we can’t always use
one: The Array may be too large, we may not know its length during development, or we
may want to keep its length flexible. Then I recommend the following techniques for
creating, and possibly filling, Arrays.
31.7.1 Do we need to create an empty Array that we’ll fill completely later on?
Note that the result has three holes (empty slots) – the last comma in an Array literal is
always ignored.
https://exploringjs.com/impatient-js/ch_arrays.html 17/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
Caveat: If we use .fill() with an object, then each Array element will refer to this object
(sharing it).
For large sizes, the temporary Array can consume quite a bit of memory. The following
approach doesn’t have this downside but is less self-descriptive:
Here is an alternative, slightly hacky technique for creating integer ranges that start at
zero:
https://exploringjs.com/impatient-js/ch_arrays.html 18/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
Array.from(createRange(4)),
[0, 1, 2, 3]);
This works because .keys() treats holes like undefined elements and lists their indices.
31.7.5 Use a Typed Array if the elements are all integers or all floats
When dealing with Arrays of integers or floats, we should consider Typed Arrays, which
were created for this purpose.
JavaScript does not have real multidimensional Arrays; we need to resort to Arrays whose
elements are Arrays:
function initMultiArray(...dimensions) {
function initMultiArrayRec(dimIndex) {
if (dimIndex >= dimensions.length) {
return 0;
} else {
const dim = dimensions[dimIndex];
const arr = [];
for (let i=0; i<dim; i++) {
arr.push(initMultiArrayRec(dimIndex+1));
}
return arr;
}
}
return initMultiArrayRec(0);
}
https://exploringjs.com/impatient-js/ch_arrays.html 19/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
In this section, we look at phenomena we don’t encounter often when working with
Arrays.
You’d think that Array elements are special because we are accessing them via numbers.
But the square brackets operator [] for doing so is the same operator that is used for
accessing properties. It coerces any value (that is not a symbol) to a string. Therefore,
Array elements are (almost) normal properties (line A) and it doesn’t matter if we use
numbers or strings as indices (lines B and C):
To make matters even more confusing, this is only how the language specification defines
things (the theory of JavaScript, if you will). Most JavaScript engines optimize under the
hood and do use actual integers to access Array elements (the practice of JavaScript, if you
will).
Property keys (strings!) that are used for Array elements are called indices. A string str is
an index if converting it to a 32-bit unsigned integer and back results in the original value.
Written as a formula:
When listing property keys, indices are treated specially – they always come first and are
sorted like numbers ('2' comes before '10'):
assert.deepEqual(
https://exploringjs.com/impatient-js/ch_arrays.html 20/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
Object.keys(arr),
['0', '1', 'prop']);
Note that .length, .entries() and .keys() treat Array indices as numbers and ignore non-
index properties:
assert.equal(arr.length, 2);
assert.deepEqual(
Array.from(arr.keys()), [0, 1]);
assert.deepEqual(
Array.from(arr.entries()), [[0, 'a'], [1, 'b']]);
We used Array.from() to convert the iterables returned by .keys() and .entries() to Arrays.
An Array arr is dense if all indices i, with 0 ≤ i < arr.length, exist. That is, the indices
form a contiguous range.
An Array is sparse if the range of indices has holes in it. That is, some indices are
missing.
Arrays can be sparse in JavaScript because Arrays are actually dictionaries from indices to
values.
So far, we have only seen dense Arrays and it’s indeed recommended to avoid holes:
They make our code more complicated and are not handled consistently by Array
methods. Additionally, JavaScript engines optimize dense Arrays, making them faster.
In line A, we are using Object.keys() because arr.keys() treats holes as if they were
undefined elements and does not reveal them.
Alas, there are many different ways in which Array operations treat holes.
Object.keys() works differently than .keys() (strings vs. numbers, holes don’t have keys):
> Array.from(['a',,'b'].keys())
[ 0, 1, 2 ]
https://exploringjs.com/impatient-js/ch_arrays.html 22/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
> Object.keys(['a',,'b'])
[ '0', '2' ]
There is no rule to remember here. If it ever matters how an Array operation treats holes,
the best approach is to do a quick test in a console.
JavaScript’s Array is quite flexible and more like a combination of array, stack, and queue.
This section explores ways of adding and removing Array elements. Most operations can
be performed both destructively (modifying the Array) and non-destructively (producing a
modified copy).
In the following code, we destructively prepend single elements to arr1 and an Array to
arr2:
https://exploringjs.com/impatient-js/ch_arrays.html 23/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
In the following code, we destructively append single elements to arr1 and an Array to
arr2:
.splice() is covered in more detail in the quick reference at the end of this chapter.
Destructuring via a rest element lets us non-destructively remove elements from the
beginning of an Array (destructuring is covered later).
Alas, a rest element must come last in an Array. Therefore, we can only use it to extract
suffixes.
exercises/arrays/queue_via_array_test.mjs
In this section, we take a look at Array methods for iterating over Arrays and for
transforming Arrays.
All iteration and transformation methods use callbacks. The former feed all iterated values
to their callbacks; the latter ask their callbacks how to transform Arrays.
That is, the callback gets three parameters (it is free to ignore any of them):
value is the most important one. This parameter holds the iterated value that is
currently being processed.
index can additionally tell the callback what the index of the iterated value is.
https://exploringjs.com/impatient-js/ch_arrays.html 25/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
arraypoints to the current Array (the receiver of the method call). Some algorithms
need to refer to the whole Array – e.g., to search it for answers. This parameter lets us
write reusable callbacks for such algorithms.
What the callback is expected to return depends on the method it is passed to. Possibilities
include:
.map() fills its result with the values returned by its callback:
.find() returns the first Array element for which its callback returns true:
.find() returns the first element for which its callback returns a truthy value (and
undefined if it can’t find anything):
.findIndex() returns the index of the first element for which its callback returns a truthy
value (and -1 if it can’t find anything):
return -1;
}
.map() returns a modified copy of the receiver. The elements of the copy are the results of
applying map’s callback to the elements of the receiver.
exercises/arrays/number_lines_test.mjs
.flatMap<U>(
callback: (value: T, index: number, array: T[]) => U|Array<U>,
thisValue?: any
): U[]
Both .map() and .flatMap() take a function callback as a parameter that controls how an
input Array is translated to an output Array:
https://exploringjs.com/impatient-js/ch_arrays.html 27/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
With .map(), each input Array element is translated to exactly one output element.
That is, callback returns a single value.
With .flatMap(), each input Array element is translated to zero or more output
elements. That is, callback returns an Array of values (it can also return non-Array
values, but that is rare).
We’ll consider use cases next, before exploring how this method could be implemented.
The result of the Array method .map() always has the same length as the Array it is
invoked on. That is, its callback can’t skip Array elements it isn’t interested in. The ability
of .flatMap() to do so is useful in the next example.
We will use the following function processArray() to create an Array that we’ll then filter
and map via .flatMap():
function throwIfNegative(value) {
if (value < 0) {
throw new Error('Illegal value: '+value);
}
return value;
}
We can now use .flatMap() to extract just the values or just the errors from results:
31.11.4.2 Use case: mapping single input values to multiple output values
The Array method .map() maps each input Array element to one output element. But what
if we want to map it to multiple output elements?
function stringsToCodePoints(strs) {
return strs.flatMap(str => Array.from(str));
}
We can implement .flatMap() as follows. Note: This implementation is simpler than the
built-in version, which, for example, performs more checks.
https://exploringjs.com/impatient-js/ch_arrays.html 29/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
Exercises: .flatMap()
exercises/arrays/convert_to_numbers_test.mjs
exercises/arrays/replace_objects_test.mjs
The Array method .filter() returns an Array collecting all elements for which the
callback returns a truthy value.
For example:
exercises/arrays/remove_empty_lines_filter_test.mjs
https://exploringjs.com/impatient-js/ch_arrays.html 30/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
reduce is also known as foldl (“fold left”) in functional programming and popular there.
One caveat is that it can make code difficult to understand.
.reduce<U>(
callback: (accumulator: U, element: T, index: number, array: T[]) => U,
init?: U)
: U
T is the type of the Array elements, U is the type of the summary. The two may or may not
be different. accumulator is just another name for “summary”.
To compute the summary of an Array arr, .reduce() feeds all Array elements to its
callback one at a time:
callback combines the previously computed summary (stored in its parameter accumulator)
with the current Array element and returns the next accumulator. The result of .reduce() is
the final accumulator – the last result of callback after it has visited all elements.
In other words: callback does most of the work; .reduce() just invokes it in a useful
manner.
We could say that the callback folds Array elements into the accumulator. That’s why this
operation is called “fold” in functional programming.
https://exploringjs.com/impatient-js/ch_arrays.html 31/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
Let’s look at an example of .reduce() in action: function addAll() computes the sum of all
numbers in an Array arr.
function addAll(arr) {
const startSum = 0;
const callback = (sum, element) => sum + element;
return arr.reduce(callback, startSum);
}
assert.equal(addAll([1, 2, 3]), 6); // (A)
assert.equal(addAll([7, -4, 2]), 5);
In this case, the accumulator holds the sum of all Array elements that callback has already
visited.
How was the result 6 derived from the Array in line A? Via the following invocations of
callback:
callback(0, 1) --> 1
callback(1, 2) --> 3
callback(3, 3) --> 6
Notes:
The first parameters are the current accumulators (starting with parameter init of
.reduce()).
The second parameters are the current Array elements.
The results are the next accumulators.
The last result of callback is also the result of .reduce().
function addAll(arr) {
let sum = 0;
for (const element of arr) {
sum = sum + element;
}
return sum;
}
It’s hard to say which of the two implementations is “better”: the one based on .reduce() is
a little more concise, while the one based on for-of may be a little easier to understand –
especially if someone is not familiar with functional programming.
https://exploringjs.com/impatient-js/ch_arrays.html 32/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
One limitation of .reduce() is that we can’t finish early (in a for-of loop, we can break).
Here, we always immediately return the result once we have found it.
Function double(arr) returns a copy of inArr whose elements are all multiplied by 2:
function double(inArr) {
return inArr.reduce(
(outArr, element) => {
outArr.push(element * 2);
return outArr;
},
[]);
}
assert.deepEqual(
double([1, 2, 3]),
[2, 4, 6]);
We modify the initial value [] by pushing into it. A non-destructive, more functional
version of double() looks as follows:
https://exploringjs.com/impatient-js/ch_arrays.html 33/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
function double(inArr) {
return inArr.reduce(
// Don’t change `outArr`, return a fresh Array
(outArr, element) => [...outArr, element * 2],
[]);
}
assert.deepEqual(
double([1, 2, 3]),
[2, 4, 6]);
This version is more elegant but also slower and uses more memory.
Exercises: .reduce()
By default, .sort() sorts string representations of the elements. These representations are
compared via <. This operator compares lexicographically (the first characters are most
significant). We can see that when sorting numbers:
When sorting human-language strings, we need to be aware that they are compared
according to their code unit values (char codes):
All unaccented uppercase letters come before all unaccented lowercase letters, which
come before all accented letters. We can use Intl, the JavaScript internationalization API if
we want proper sorting for human languages.
https://exploringjs.com/impatient-js/ch_arrays.html 34/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
We can customize the sort order via the parameter compareFunc, which must return a
number that is:
negative if a < b
zero if a === b
positive if a > b
function compareNumbers(a, b) {
if (a < b) {
return -1;
} else if (a === b) {
return 0;
} else {
return 1;
}
}
assert.deepEqual(
[200, 3, 10].sort(compareNumbers),
[3, 10, 200]);
It is cryptic.
https://exploringjs.com/impatient-js/ch_arrays.html 35/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
We also need to use a compare function if we want to sort objects. As an example, the
following code shows how to sort objects by age.
exercises/arrays/sort_objects_test.mjs
Legend:
new Array() creates an empty Array. However, I recommend to always use [] instead.
https://exploringjs.com/impatient-js/ch_arrays.html 36/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
Examples:
This static method is mainly useful for subclasses of Array, where it serves as a
custom Array literal:
assert.equal(
MyArray.of('a', 'b') instanceof MyArray, true);
Returns the Array element at index. If index is negative, it is added to .length before it
is used (-1 becomes this.length-1, etc.).
Returns a new Array that is the concatenation of the receiver and all items. Non-
Array parameters (such as 'b' in the following example) are treated as if they were
Arrays with single elements.
Copies the elements whose indices range from (including) start to (excluding) end to
indices starting with target. Overlapping is handled correctly.
https://exploringjs.com/impatient-js/ch_arrays.html 37/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
Returns true if callback returns a truthy value for every element. Otherwise, it
returns false. It stops as soon as it receives a falsy value. This method corresponds to
universal quantification (“for all”, ∀) in mathematics.
Assigns value to every index between (including) start and (excluding) end.
Caveat: Don’t use this method to fill an Array with an object obj; then each element
will refer to obj (sharing it). In this case, it’s better to use Array.from().
.filter(callback: (value: T, index: number, array: Array<T>) => any, thisArg?: any):
Returns an Array with only those elements for which callback returns a truthy value.
https://exploringjs.com/impatient-js/ch_arrays.html 38/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
.find(predicate: (value: T, index: number, obj: T[]) => boolean, thisArg?: any): T |
The result is the first element for which predicate returns a truthy value. If there is no
such element, the result is undefined.
The result is the index of the first element for which predicate returns a truthy value.
If there is no such element, the result is -1.
“Flattens” an Array: It descends into the Arrays that are nested inside the input
Array and creates a copy where all values it finds at level depth or lower are moved to
the top level.
The result is produced by invoking callback() for each element of the original Array
and concatenating the Arrays it returns.
https://exploringjs.com/impatient-js/ch_arrays.html 39/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
// Output:
// 'a', 0
// 'b', 1
A for-of loop is usually a better choice: it’s faster, supports break and can iterate over
arbitrary iterables.
Returns true if the receiver has an element whose value is searchElement and false,
otherwise. Searching starts at index fromIndex.
Returns the index of the first element that is strictly equal to searchElement. Returns -1
if there is no such element. Starts searching at index fromIndex, visiting higher indices
next.
https://exploringjs.com/impatient-js/ch_arrays.html 40/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
Returns the index of the last element that is strictly equal to searchElement. Returns -1
if there is no such element. Starts searching at index fromIndex, visiting lower indices
next.
Returns a new Array, in which every element is the result of mapFunc being applied to
the corresponding element of the receiver.
https://exploringjs.com/impatient-js/ch_arrays.html 41/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
Removes and returns the last element of the receiver. That is, it treats the end of the
receiver as a stack. The opposite of .push().
Adds zero or more items to the end of the receiver. That is, it treats the end of the
receiver as a stack. The return value is the length of the receiver after the change. The
opposite of .pop().
This method produces a summary of the receiver: it feeds all Array elements to
callback,which combines a current summary (in parameter accumulator) with the
current Array element and returns the next accumulator:
The result of .reduce() is the last result of callback after it has visited all Array
elements.
https://exploringjs.com/impatient-js/ch_arrays.html 42/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
If no init is provided, the Array element at index 0 is used and the element at index 1
is visited first. Therefore, the Array must have at least length 1.
Works like .reduce(), but visits the Array elements backward, starting with the last
element.
Rearranges the elements of the receiver so that they are in reverse order and then
returns the receiver.
Removes and returns the first element of the receiver. The opposite of .unshift().
Returns a new Array containing the elements of the receiver whose indices are
between (including) start and (excluding) end.
Returns true if callback returns a truthy value for at least one element. Otherwise, it
returns false. It stops as soon as it receives a truthy value. This method corresponds
to existential quantification (“exists”, ∃) in mathematics.
Sorts the receiver and returns it. By default, it sorts string representations of the
elements. It does so lexicographically and according to the code unit values (char
codes) of the characters:
We can customize the sort order via compareFunc, which returns a number that is:
negative if a < b
zero if a === b
positive if a > b
.sort() is stable
https://exploringjs.com/impatient-js/ch_arrays.html 44/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
At index start, it removes deleteCount elements and inserts the items. It returns the
deleted elements.
Converts all elements to strings via String(), concatenates them while separating
them with commas, and returns the result.
Inserts the items at the beginning of the receiver and returns its length after this
modification.
https://exploringjs.com/impatient-js/ch_arrays.html 45/46
5/9/24, 5:53 PM Arrays (`Array`) • JavaScript for impatient programmers (ES2022 edition)
31.13.4 Sources
Quiz
https://exploringjs.com/impatient-js/ch_arrays.html 46/46