1/103
Javascript Array
at() supports negative indexes counted from the end.const a = ['a', 'b', 'c'];
a.at(-1) // 'c'
a.at(-2) // 'b'
a.at(9) // undefineda[-1] accesses a property named '-1', not the last element.new Array(3) creates an array of length 3 with three holes.[3] creates an array containing the number 3.Array.from() uses the string iterator, which iterates Unicode code points; split('') splits UTF-16 code units.Array.from('A😀') // ['A', '😀']
'A😀'.split('').length // 3slice(start, end) copies a range and does not mutate.splice(start, deleteCount, ...items) edits the original and returns the removed elements.slice, but a deletion count for splice.includes uses SameValueZero and recognizes NaN. indexOf uses strict equality and cannot find it.[NaN].includes(NaN) // true
[NaN].indexOf(NaN) // -10 and -0 as equal.[].some(x => true) // false
[].every(x => false) // truesome; no element contradicts every. Neither callback runs.(element, index, array).['a', 'b'].map((value, index) => index + ':' + value)
// ['0:a', '1:b']for (const value of [10, 20, 30]) {
console.log(value);
}break, continue, and, inside an async function, await.const a = ['a', 'b'];
for (let i = 0; i < a.length; i++) {
console.log(i, a[i]);
}i < a.length, not i <= a.length, to avoid an extra out-of-bounds iteration.forEach ignores the promises returned by its callbacks and returns immediately.for (const x of items) { await save(x); }await Promise.all(items.map(x => save(x)));save function.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]push, pop, shift, unshift, splice, sort, reverse, fill, and copyWithin.length also mutate it.map supplies (value, index, array), while parseInt interprets its second argument as the radix.['1', '2', '3'].map(parseInt) // [1, NaN, NaN]map(s => parseInt(s, 10)) or map(Number) when its conversion rules suit your inputs.