Javascript Array

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/103

flashcard set

Earn XP

Description and Tags

Javascript Array

104 Terms

1
New cards
#separator:Tab
2
New cards
#html:true
3
New cards
#columns:Front
Back
4
New cards
What is a JavaScript array?
An ordered, zero-indexed collection. Arrays can grow or shrink and can hold values of different types.<br><code>const items = [42, 'hello', true];</code><br>Arrays are objects, not a separate primitive type.
5
New cards
How do you create an array using an array literal?
Use square brackets.<br><code>const empty = [];<br>const fruits = ['apple', 'banana', 'cherry'];</code><br>Array literals are generally clearer than the <code>Array</code> constructor.
6
New cards
How do you read and update an array element by index?
The first element has index <code>0</code>.<br><code>const a = ['red', 'blue'];<br>a[0] // 'red'<br>a[1] = 'green';<br>// a is ['red', 'green']</code>
7
New cards
What does an array's <code>length</code> represent?
One more than its highest array index, or <code>0</code> for an empty array. It is not necessarily the number of present elements in a sparse array.<br><code>['a', 'b', 'c'].length // 3</code>
8
New cards
What happens when you read an out-of-bounds array index?
For an ordinary array without an inherited property at that index, you get <code>undefined</code>, not an exception.<br><code>const a = [10, 20];<br>a[5] // undefined</code>
9
New cards
How do you get the last element with <code>at()</code>?
at() supports negative indexes counted from the end.
const a = ['a', 'b', 'c'];
a.at(-1) // 'c'
a.at(-2) // 'b'
a.at(9) // undefined

a[-1] accesses a property named '-1', not the last element.
10
New cards
What happens when you reduce an array's <code>length</code>?
Elements at indexes greater than or equal to the new length are removed.<br><code>const a = [1, 2, 3];<br>a.length = 1;<br>// a is [1]</code><br><code>a.length = 0</code> clears the array in place.
11
New cards
What happens when you increase an array's <code>length</code> or assign beyond its end?
You create empty slots (holes), not explicit <code>undefined</code> elements.<br><code>const a = [1];<br>a.length = 3;<br>1 in a // false</code><br><code>a[5] = 9;</code> makes its length <code>6</code> and leaves holes between existing elements.
12
New cards
How do you reliably check whether a value is an array?
Use <code>Array.isArray(value)</code>.<br><code>Array.isArray([]) // true<br>Array.isArray({}) // false<br>typeof [] // 'object'</code><br>It also recognizes arrays created in another realm, such as an iframe.
13
New cards
What is the difference between <code>new Array(3)</code> and <code>[3]</code>?
new Array(3) creates an array of length 3 with three holes.
[3] creates an array containing the number 3.
With a single numeric argument, the constructor treats it as a length.
14
New cards
What does <code>Array.of()</code> do?
Creates an array containing its arguments, even when there is just one number.<br><code>Array.of(3) // [3]<br>Array.of(1, 2, 3) // [1, 2, 3]<br>Array.of() // []</code>
15
New cards
How do you convert an iterable or array-like object into an array?
Use <code>Array.from()</code>.<br><code>Array.from(new Set([1, 2])) // [1, 2]<br>Array.from({0: 'a', 1: 'b', length: 2}) // ['a', 'b']</code><br>Array-like objects have a <code>length</code> and indexed properties; they need not be iterable.
16
New cards
How can <code>Array.from()</code> generate a sequence of numbers?
Pass a length and a mapping callback.<br><code>Array.from({length: 5}, (_, i) =&gt; i + 1)<br>// [1, 2, 3, 4, 5]</code><br>The callback receives the element value and index; here the value is unused.
17
New cards
How does <code>Array.from(string)</code> differ from <code>string.split('')</code> for emoji?
Array.from() uses the string iterator, which iterates Unicode code points; split('') splits UTF-16 code units.
Array.from('A😀') // ['A', '😀']
'A😀'.split('').length // 3

Code points are still not necessarily whole user-perceived characters, such as joined emoji sequences.
18
New cards
What does <code>push()</code> do and return?
Adds one or more elements to the end, mutates the array, and returns the new length.<br><code>const a = [1];<br>a.push(2, 3) // 3<br>// a is [1, 2, 3]</code>
19
New cards
What does <code>pop()</code> do and return?
Removes the last element, mutates the array, and returns the removed value.<br><code>const a = [1, 2, 3];<br>a.pop() // 3<br>// a is [1, 2]</code>
20
New cards
What does <code>unshift()</code> do and return?
Adds one or more elements to the beginning, mutates the array, and returns the new length.<br><code>const a = [3];<br>a.unshift(1, 2) // 3<br>// a is [1, 2, 3]</code>
21
New cards
What does <code>shift()</code> do and return?
Removes the first element, mutates the array, and returns the removed value.<br><code>const a = [1, 2, 3];<br>a.shift() // 1<br>// a is [2, 3]</code>
22
New cards
What do <code>pop()</code> and <code>shift()</code> return on an empty array?
Both return <code>undefined</code> and leave the array empty.<br><code>[].pop() // undefined<br>[].shift() // undefined</code>
23
New cards
How do you remove elements with <code>splice()</code>?
Use <code>splice(start, deleteCount)</code>. It mutates the array and returns an array of removed elements.<br><code>const a = ['a', 'b', 'c', 'd'];<br>a.splice(1, 2) // ['b', 'c']<br>// a is ['a', 'd']</code>
24
New cards
How do you insert elements without deleting any using <code>splice()</code>?
Set <code>deleteCount</code> to <code>0</code> and pass the new elements.<br><code>const a = [1, 4];<br>a.splice(1, 0, 2, 3) // []<br>// a is [1, 2, 3, 4]</code>
25
New cards
How do you replace elements with <code>splice()</code>?
Delete existing elements and supply replacements in the same call.<br><code>const a = ['a', 'b', 'c'];<br>a.splice(1, 1, 'B') // ['b']<br>// a is ['a', 'B', 'c']</code>
26
New cards
How do <code>splice(1)</code> and <code>splice(1, undefined)</code> differ?
With an omitted <code>deleteCount</code>, elements from the start index to the end are removed. Explicit <code>undefined</code> converts to a delete count of 0.<br><code>[1, 2, 3].splice(1) // [2, 3]<br>[1, 2, 3].splice(1, undefined) // []</code>
27
New cards
Why is <code>delete a[i]</code> usually wrong for removing an array element?
It removes the indexed property but leaves a hole and does not shorten the array.<br><code>const a = [1, 2, 3];<br>delete a[1];<br>a.length // 3<br>1 in a // false</code><br>Use <code>splice(i, 1)</code> to remove and close the gap.
28
New cards
What does <code>slice(start, end)</code> do?
Returns a shallow copy of the selected range without mutating the original. <code>start</code> is inclusive; <code>end</code> is exclusive.<br><code>const a = [10, 20, 30, 40];<br>a.slice(1, 3) // [20, 30]<br>// a is unchanged</code><br>Omitting <code>end</code> selects through the end.
29
New cards
How do negative indexes work in <code>slice()</code>?
They count backward from the end.<br><code>[1, 2, 3, 4].slice(-2) // [3, 4]<br>[1, 2, 3, 4].slice(1, -1) // [2, 3]</code>
30
New cards
What is the key difference between <code>slice()</code> and <code>splice()</code>?
slice(start, end) copies a range and does not mutate.
splice(start, deleteCount, ...items) edits the original and returns the removed elements.
The second argument is an end index for slice, but a deletion count for splice.
31
New cards
What does <code>concat()</code> do?
Returns a new array combining the receiver with supplied values or arrays, without mutating the originals. Ordinary array arguments are spread one level.<br><code>[1, 2].concat([3, 4], 5) // [1, 2, 3, 4, 5]<br>[1].concat([[2]]) // [1, [2]]</code>
32
New cards
How do you merge arrays with spread syntax?
Spread their elements into a new array.<br><code>const a = [1, 2];<br>const b = [3, 4];<br>const merged = [...a, ...b];<br>// [1, 2, 3, 4]</code><br>The original arrays are not mutated.
33
New cards
Does assigning an array to another variable copy it?
No. Both variables refer to the same array.<br><code>const a = [1, 2];<br>const b = a;<br>b.push(3);<br>// a is [1, 2, 3]<br>a === b // true</code>
34
New cards
What does it mean that spread, <code>slice()</code>, and <code>Array.from()</code> make shallow copies?
They create a new outer array, but nested objects remain shared references.<br><code>const a = [{n: 1}];<br>const b = [...a];<br>b[0].n = 9;<br>a[0].n // 9<br>a === b // false</code>
35
New cards
How can you deeply copy an array of structured-cloneable values?
Use <code>structuredClone()</code> in an environment that supports it.<br><code>const a = [{n: 1}];<br>const b = structuredClone(a);<br>b[0].n = 9;<br>a[0].n // 1</code><br>It is not universal: functions, for example, cannot be structured-cloned.
36
New cards
What does <code>indexOf()</code> return?
The index of the first matching element, or <code>-1</code> when not found. It uses strict-equality comparison.<br><code>['a', 'b', 'a'].indexOf('a') // 0<br>['a', 'b'].indexOf('z') // -1</code><br>An optional second argument specifies where to start searching.
37
New cards
What does <code>lastIndexOf()</code> return?
The index of the last matching element, or <code>-1</code> when not found. It searches backward using strict-equality comparison.<br><code>['a', 'b', 'a'].lastIndexOf('a') // 2</code>
38
New cards
What does <code>includes()</code> return?
A boolean indicating whether the array contains a value.<br><code>[1, 2, 3].includes(2) // true<br>[1, 2, 3].includes(9) // false<br>[1, 2, 3].includes(1, 1) // false</code><br>The optional second argument is the starting index.
39
New cards
How do <code>includes()</code> and <code>indexOf()</code> differ for <code>NaN</code>?
includes uses SameValueZero and recognizes NaN. indexOf uses strict equality and cannot find it.
[NaN].includes(NaN) // true
[NaN].indexOf(NaN) // -1

Both treat 0 and -0 as equal.
40
New cards
How do array searches compare objects?
By reference identity, not by matching their properties.<br><code>const item = {id: 1};<br>[item].includes(item) // true<br>[item].includes({id: 1}) // false</code><br>Use a predicate such as <code>find(x =&gt; x.id === 1)</code> to search by a property.
41
New cards
What does <code>find()</code> return?
The first element whose predicate is truthy, or <code>undefined</code> if none matches.<br><code>[3, 8, 10].find(x =&gt; x &gt; 5) // 8</code><br>A returned <code>undefined</code> can also be a matching element's value; use <code>findIndex</code> when you need to distinguish the cases.
42
New cards
What does <code>findIndex()</code> return?
The index of the first element whose predicate is truthy, or <code>-1</code> if none matches.<br><code>[3, 8, 10].findIndex(x =&gt; x &gt; 5) // 1</code>
43
New cards
What does <code>findLast()</code> return?
The last element whose predicate is truthy, searching from the end, or <code>undefined</code> if none matches.<br><code>[3, 8, 10].findLast(x =&gt; x &gt; 5) // 10</code>
44
New cards
What does <code>findLastIndex()</code> return?
The index of the last element whose predicate is truthy, or <code>-1</code> if none matches.<br><code>[3, 8, 10].findLastIndex(x =&gt; x &gt; 5) // 2</code>
45
New cards
What does <code>some()</code> do?
Returns <code>true</code> as soon as at least one visited element passes the predicate; otherwise returns <code>false</code>.<br><code>[1, 3, 4].some(x =&gt; x % 2 === 0) // true</code><br>It short-circuits after the first success.
46
New cards
What does <code>every()</code> do?
Returns <code>false</code> as soon as a visited element fails the predicate; otherwise returns <code>true</code>.<br><code>[2, 4, 6].every(x =&gt; x % 2 === 0) // true</code><br>It short-circuits after the first failure.
47
New cards
What do <code>some()</code> and <code>every()</code> return for an empty array?
[].some(x => true) // false
[].every(x => false) // true

No element can satisfy some; no element contradicts every. Neither callback runs.
48
New cards
What arguments do callbacks for methods such as <code>map()</code>, <code>filter()</code>, and <code>forEach()</code> receive?
(element, index, array).
['a', 'b'].map((value, index) => index + ':' + value)
// ['0:a', '1:b']

The third argument is the array being traversed, not the result being built.
49
New cards
How do you iterate over array values with <code>for...of</code>?
for (const value of [10, 20, 30]) {
console.log(value);
}

You can use break, continue, and, inside an async function, await.
50
New cards
How do you iterate with explicit indexes using a classic <code>for</code> loop?
const a = ['a', 'b'];
for (let i = 0; i < a.length; i++) {
console.log(i, a[i]);
}

Use i < a.length, not i <= a.length, to avoid an extra out-of-bounds iteration.
51
New cards
What does <code>forEach()</code> do and return?
Runs a callback for each present element, in index order, and returns <code>undefined</code>.<br><code>[1, 2].forEach(x =&gt; console.log(x));</code><br>Use it for side effects; callback return values are discarded.
52
New cards
Can you stop <code>forEach()</code> early with <code>break</code> or a callback <code>return</code>?
No. <code>break</code> cannot break out of a <code>forEach</code> callback, and <code>return</code> only exits that callback invocation.<br>Use <code>for...of</code> for loop control, or <code>some</code>/<code>find</code> for short-circuit searches.
53
New cards
Why does <code>forEach(async ...)</code> not wait for asynchronous work?
forEach ignores the promises returned by its callbacks and returns immediately.
Sequential: for (const x of items) { await save(x); }
Concurrent: await Promise.all(items.map(x => save(x)));
The examples assume an async function and a suitable save function.
54
New cards
Why should you avoid <code>for...in</code> for ordinary array iteration?
It iterates enumerable string property names, including extra properties and inherited enumerable properties, rather than just array values.<br>Use <code>for...of</code> for values or <code>entries()</code> for index/value pairs.
55
New cards
What does <code>map()</code> do?
Returns a new array containing each visited element's callback result, without itself mutating the original.<br><code>[1, 2, 3].map(x =&gt; x * 2) // [2, 4, 6]</code><br>On a dense array, there is one output element per input element.
56
New cards
What does <code>filter()</code> do?
Returns a new array of elements whose predicate is truthy, preserving their order.<br><code>[1, 2, 3, 4].filter(x =&gt; x % 2 === 0)<br>// [2, 4]</code><br>It keeps the original element values, not the predicate results.
57
New cards
How do you sum an array using <code>reduce()</code>?
Pass a reducer and an initial accumulator.<br><code>[1, 2, 3].reduce((sum, x) =&gt; sum + x, 0) // 6</code><br>The reducer receives <code>(accumulator, currentValue, index, array)</code>. Its return value becomes the next accumulator.
58
New cards
What happens when <code>reduce()</code> has no initial value?
It uses the first present element as the accumulator and begins callbacks at the next present element.<br><code>[1, 2, 3].reduce((a, b) =&gt; a + b) // 6</code><br>With no present elements, it throws <code>TypeError</code>.<br><code>[].reduce((a, b) =&gt; a + b, 0) // 0</code>
59
New cards
What does <code>reduceRight()</code> do?
Reduces from right to left rather than left to right.<br><code>['a', 'b', 'c'].reduceRight((acc, x) =&gt; acc + x, '')<br>// 'cba'</code><br>Direction matters for operations that are not commutative.
60
New cards
When should you use <code>map()</code> instead of <code>forEach()</code>?
Use <code>map</code> when you need a new array of transformed values.<br>Use <code>forEach</code> when you only need side effects.<br><code>const doubled = [1, 2].map(x =&gt; x * 2);</code><br>Using <code>map</code> and discarding its result usually expresses the wrong intent.
61
New cards
What does <code>filter(Boolean)</code> remove?
All falsy values, not just missing values.<br><code>[0, 1, '', 'x', false, null, undefined, NaN].filter(Boolean)<br>// [1, 'x']</code><br>To remove only <code>null</code> and <code>undefined</code>, use <code>filter(x =&gt; x !== null &amp;&amp; x !== undefined)</code>.
62
New cards
How do you return an object literal from a concise arrow callback in <code>map()</code>?
Wrap the object literal in parentheses.<br><code>[1, 2].map(n =&gt; ({value: n}))<br>// [{value: 1}, {value: 2}]</code><br>Without parentheses, braces are parsed as a function body rather than the returned object expression.
63
New cards
What does <code>flat()</code> do, and what is its default depth?
Returns a new array with nested arrays flattened to the specified depth; the default is <code>1</code>.<br><code>[1, [2, [3]]].flat() // [1, 2, [3]]<br>[1, [2, [3]]].flat(Infinity) // [1, 2, 3]</code><br>It does not mutate the original.
64
New cards
What does <code>flatMap()</code> do?
Maps each visited element, then flattens the mapped results by one level.<br><code>[1, 2].flatMap(x =&gt; [x, x * 10])<br>// [1, 10, 2, 20]</code><br>Returning <code>[]</code> omits an element; returning multiple array elements expands it.
65
New cards
How can you combine <code>filter()</code> and <code>map()</code> in a pipeline?
Filter for the elements you want, then transform them.<br><code>[1, 2, 3, 4]<br> .filter(x =&gt; x % 2 === 0)<br> .map(x =&gt; x * 10)<br>// [20, 40]</code><br>Order matters: filtering before transforming is not always equivalent to the reverse.
66
New cards
Why can default <code>sort()</code> produce unexpected results for numbers?
It compares string representations in UTF-16 code-unit order, not numeric value.<br><code>[2, 10, 1].sort() // [1, 10, 2]</code><br>Supply a numeric comparator for numbers.
67
New cards
How do you sort numbers in ascending order?
Use <code>(a, b) =&gt; a - b</code> for ordinary finite numbers.<br><code>[10, 2, 1].sort((a, b) =&gt; a - b)<br>// [1, 2, 10]</code><br><code>sort()</code> mutates the array.
68
New cards
How do you sort numbers in descending order?
Use <code>(a, b) =&gt; b - a</code> for ordinary finite numbers.<br><code>[10, 2, 1].sort((a, b) =&gt; b - a)<br>// [10, 2, 1]</code>
69
New cards
How do you sort objects by a numeric property or a human-language string?
Numeric property: <code>users.sort((a, b) =&gt; a.age - b.age)</code>.<br>Locale-aware string comparison: <code>users.sort((a, b) =&gt; a.name.localeCompare(b.name))</code>.<br>String ordering can depend on locale; provide a locale when you need a specific one.
70
New cards
What must a <code>sort()</code> comparator return?
A negative number if <code>a</code> comes before <code>b</code>, a positive number if it comes after, or <code>0</code> for equal ordering.<br>It should be consistent, antisymmetric, and transitive.<br>Returning a boolean such as <code>a &gt; b</code> is not a correct general comparator.
71
New cards
Is JavaScript array sorting stable?
Yes, stable sorting is required by ECMAScript 2019 and later: elements that compare equal retain their relative order.<br><code>[{k: 1, id: 'a'}, {k: 1, id: 'b'}].sort((a, b) =&gt; a.k - b.k)</code><br>The IDs remain in the order <code>'a'</code>, <code>'b'</code>.
72
New cards
Does <code>sort()</code> return a new array?
No. It mutates and returns the same array reference.<br><code>const a = [3, 1, 2];<br>const result = a.sort((x, y) =&gt; x - y);<br>result === a // true</code><br>Use <code>toSorted()</code> or copy before sorting when you need to preserve the original.
73
New cards
What does <code>toSorted()</code> do?
Returns a shallow sorted copy without mutating the original.<br><code>const a = [3, 1, 2];<br>a.toSorted((x, y) =&gt; x - y) // [1, 2, 3]<br>// a is still [3, 1, 2]</code><br>It is a modern method; check target-runtime support. For dense arrays, <code>[...a].sort(comparator)</code> is an older alternative.
74
New cards
What does <code>reverse()</code> do and return?
Reverses the array in place and returns the same array reference.<br><code>const a = [1, 2, 3];<br>a.reverse() // [3, 2, 1]<br>// a is now [3, 2, 1]</code>
75
New cards
What does <code>toReversed()</code> do?
Returns a shallow reversed copy without mutating the original.<br><code>const a = [1, 2, 3];<br>a.toReversed() // [3, 2, 1]<br>// a is unchanged</code><br>It is a modern method; check runtime support. For dense arrays, <code>[...a].reverse()</code> is an older alternative.
76
New cards
What does <code>toSpliced()</code> return, and how does that differ from <code>splice()</code>?
toSpliced() returns the edited copy, leaving the original unchanged. splice() mutates and returns the removed elements.
const a = [1, 2, 3];
a.toSpliced(1, 1, 9) // [1, 9, 3]
// a is still [1, 2, 3]

Check target-runtime support for this modern method.
77
New cards
What does an array's <code>with(index, value)</code> method do?
Returns a shallow copy with one element replaced, without mutating the original. Negative indexes count from the end; an out-of-range index throws <code>RangeError</code>.<br><code>[1, 2, 3].with(1, 9) // [1, 9, 3]<br>[1, 2, 3].with(-1, 9) // [1, 2, 9]</code><br>Check target-runtime support for this modern method.
78
New cards
What does <code>join()</code> do?
Returns a string joining element string representations with a separator. The default separator is a comma.<br><code>['a', 'b', 'c'].join('-') // 'a-b-c'<br>[1, 2, 3].join() // '1,2,3'<br>[].join('-') // ''</code>
79
New cards
How does <code>join()</code> handle <code>null</code>, <code>undefined</code>, and holes?
Each contributes an empty string, but separators still appear.<br><code>[1, null, undefined, 4].join('-') // '1---4'<br>[1, , 3].join('-') // '1--3'</code>
80
New cards
How do you convert a delimited string into an array?
Use the string method <code>split()</code>.<br><code>'a,b,c'.split(',') // ['a', 'b', 'c']</code><br>It is not an array method. Simple splitting is not a full CSV parser because quoted delimiters need special handling.
81
New cards
What does an ordinary array's <code>toString()</code> return?
A comma-separated string, effectively using <code>join()</code> with its default separator.<br><code>[1, 2, 3].toString() // '1,2,3'</code><br>It does not produce JSON; use <code>JSON.stringify</code> when JSON serialization is needed.
82
New cards
What does <code>fill(value, start, end)</code> do?
Overwrites a range in place with the same value and returns the array. <code>start</code> is inclusive and <code>end</code> is exclusive; omitted bounds cover the whole array.<br><code>[1, 2, 3, 4].fill(0, 1, 3) // [1, 0, 0, 4]<br>new Array(3).fill(0) // [0, 0, 0]</code>
83
New cards
Why is <code>new Array(3).fill({})</code> dangerous when you want independent objects?
All slots reference the same object.<br><code>const a = new Array(3).fill({});<br>a[0].x = 1;<br>a[1].x // 1<br>a[0] === a[1] // true</code>
84
New cards
How do you create an array of independent objects?
Create a new object for each callback invocation.<br><code>const a = Array.from({length: 3}, () =&gt; ({}));<br>a[0] === a[1] // false</code><br><code>new Array(3).map(() =&gt; ({}))</code> does not work because <code>map</code> skips holes.
85
New cards
What does <code>copyWithin(target, start, end)</code> do?
Copies a range to another position in the same array, mutates it, and returns the same array. It does not change the length; <code>end</code> is exclusive.<br><code>[1, 2, 3, 4, 5].copyWithin(0, 3)<br>// [4, 5, 3, 4, 5]</code><br>Overlapping ranges are handled safely.
86
New cards
What does <code>keys()</code> return?
An iterator over indexes from <code>0</code> to <code>length - 1</code>, including indexes of holes.<br><code>[...['a', 'b'].keys()] // [0, 1]</code><br>The result is an iterator, not an array; spreading materializes it.
87
New cards
What does <code>values()</code> return?
An iterator over element values. Holes are read as <code>undefined</code> for ordinary arrays.<br><code>[...['a', 'b'].values()] // ['a', 'b']</code><br>The default array iterator used by <code>for...of</code> also iterates values.
88
New cards
How can <code>entries()</code> give you both index and value?
It returns an iterator of <code>[index, value]</code> pairs.<br><code>for (const [i, value] of ['a', 'b'].entries()) {<br> console.log(i, value);<br>}</code><br>The pairs are <code>[0, 'a']</code> and <code>[1, 'b']</code>.
89
New cards
How does array destructuring extract values and provide defaults?
It binds values by position; commas can skip positions. A default is used for <code>undefined</code>, not for <code>null</code>.<br><code>const [first, , third = 99] = [10, 20];<br>// first is 10; third is 99</code>
90
New cards
How do you collect remaining array elements with rest destructuring?
Place a rest element last.<br><code>const [first, ...rest] = [1, 2, 3];<br>// first is 1; rest is [2, 3]</code><br><code>rest</code> is a new shallow array of the remaining values.
91
New cards
How can destructuring swap two variables?
Use a temporary array on the right.<br><code>let a = 1, b = 2;<br>[a, b] = [b, a];<br>// a is 2; b is 1</code>
92
New cards
How do you remove duplicate primitive values using <code>Set</code>?
Convert the array to a Set, then spread it back into an array.<br><code>[...new Set([1, 2, 2, 3, 1])] // [1, 2, 3]</code><br>It preserves first-occurrence order and uses SameValueZero equality. Distinct objects are not deduplicated by their contents.
93
New cards
Does <code>const</code> make an array immutable?
No. It prevents rebinding the variable, but the array can still change.<br><code>const a = [1];<br>a.push(2); // allowed<br>a[0] = 9; // allowed</code><br>Assigning a new array to <code>a</code> would throw a <code>TypeError</code>.
94
New cards
What is the difference between an array hole and an explicit <code>undefined</code> element?
A hole has no own indexed property; an explicit <code>undefined</code> element does.<br><code>const hole = new Array(1);<br>const value = [undefined];<br>Object.hasOwn(hole, 0) // false<br>Object.hasOwn(value, 0) // true</code><br>Both return <code>undefined</code> when read normally.
95
New cards
How does <code>map()</code> handle holes in a sparse array?
It skips missing indexed properties and preserves the holes in the result, assuming no inherited indexed properties.<br><code>const a = [1, , 3];<br>const b = a.map(x =&gt; x * 2);<br>// b has 2, a hole, then 6<br>Object.hasOwn(b, 1) // false</code><br><code>forEach</code>, <code>filter</code>, and <code>reduce</code> also skip missing indexes; <code>filter</code> compacts its result.
96
New cards
How do <code>find()</code> and <code>includes()</code> handle holes in ordinary sparse arrays?
They read holes as <code>undefined</code>, unlike methods such as <code>map</code> that skip missing indexes.<br><code>new Array(1).includes(undefined) // true<br>new Array(1).indexOf(undefined) // -1<br>new Array(1).findIndex(x =&gt; x === undefined) // 0</code>
97
New cards
How do spread and <code>slice()</code> differ when copying a sparse array?
Spread reads holes as <code>undefined</code> and creates present elements; <code>slice</code> preserves holes for ordinary arrays.<br><code>const a = [1, , 3];<br>Object.hasOwn([...a], 1) // true<br>Object.hasOwn(a.slice(), 1) // false</code><br><code>Array.from(a)</code> also materializes holes as <code>undefined</code>.
98
New cards
Which common array operations mutate the original array?
push, pop, shift, unshift, splice, sort, reverse, fill, and copyWithin.
Index assignment and changing length also mutate it.
When sharing array references, consider who else can observe the change.
99
New cards
Do non-mutating methods prevent their callbacks from mutating data?
No. The method itself may be non-mutating while your callback still changes the source or nested objects.<br><code>const a = [{n: 1}];<br>a.map(x =&gt; { x.n++; return x; });<br>a[0].n // 2</code><br>Non-mutating does not mean deeply immutable.
100
New cards
Why does <code>['1', '2', '3'].map(parseInt)</code> give an unexpected result?
map supplies (value, index, array), while parseInt interprets its second argument as the radix.
['1', '2', '3'].map(parseInt) // [1, NaN, NaN]
Use map(s => parseInt(s, 10)) or map(Number) when its conversion rules suit your inputs.