Skip to content
  • Arrays · JavaScript

Arrays

LearnViaNotes @learnvianotes· 2 min read

Arrays are ordered, zero-indexed, dynamically sized lists that can hold any mix of values. Under the hood they are objects with numeric keys and a magic length.

Creating arrays

JavaScript
const a = [1, "two", { three: 3 }, [4]];
console.log(a, a.length);
console.log(Array.of(7), Array(3), Array(3).fill(0));
console.log(Array.from("abc"), Array.from({ length: 4 }, (_, i) => i * i));
console.log([..."hi"], Array.from(new Set([1, 1, 2])));
Output
[ 1, 'two', { three: 3 }, [ 4 ] ] 4
[ 7 ] [ <3 empty items> ] [ 0, 0, 0 ]
[ 'a', 'b', 'c' ] [ 0, 1, 4, 9 ]
[ 'h', 'i' ] [ 1, 2 ]

Adding and removing

MethodWhereMutates?Returns
push(x) / pop()EndYesnew length / removed item
unshift(x) / shift()Start (O(n))Yesnew length / removed item
splice(i, n, ...items)AnywhereYesarray of removed items
slice(i, j)Copy a rangeNonew array
concat(...arrs)JoinNonew array
toSpliced, with(i, v)Copying variants (ES2023)Nonew array
JavaScript
const arr = ["a", "b", "c", "d"];
arr.push("e");
const last = arr.pop();
arr.unshift("z");
const first = arr.shift();
console.log(arr, last, first);

const removed = arr.splice(1, 2, "X", "Y", "Z");   // at 1: remove 2, insert 3
console.log(arr, removed);
console.log(arr.slice(1, 3), arr.slice(-2), arr.with(0, "!"), arr[0]);
Output
[ 'a', 'b', 'c', 'd' ] e z
[ 'a', 'X', 'Y', 'Z', 'd' ] [ 'b', 'c' ]
[ 'X', 'Y' ] [ 'Z', 'd' ] [ '!', 'X', 'Y', 'Z', 'd' ] a

length is writable

JavaScript
const nums = [1, 2, 3, 4, 5];
nums.length = 2;                 // truncates
console.log(nums);
nums[5] = 6;                     // creates holes
console.log(nums, nums.length);
console.log(nums.at(-1), nums[nums.length - 1]);
Output
[ 1, 2 ]
[ 1, 2, <3 empty items>, 6 ] 6
6 6

Checking and converting

JavaScript
console.log(Array.isArray([]), typeof []);
console.log([1, [2, 3]].toString(), String([null, undefined, 1]));
console.log([3, 1, 2].join(" < "), "a-b-c".split("-"));
Output
true object
1,2,3 ,,1
3 < 1 < 2 [ 'a', 'b', 'c' ]

How do you empty an array?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report