Array Basics

Creating and Accessing Arrays

Example

An array is an ordered list. Indexes start at 0:

const fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0], fruits.length);
console.log(fruits.at(-1));          // last element
fruits[1] = "Orange";
console.log(fruits);
const mixed = [1, "two", { three: 3 }, [4]];
console.log(mixed.length);

Output

Apple 3
Mango
[ 'Apple', 'Orange', 'Mango' ]
4

Adding and Removing

MethodDoesChanges the array?
push(x) / pop()add / remove at the endyes
unshift(x) / shift()add / remove at the startyes
splice(i, n, ...items)remove/insert anywhereyes
slice(start, end)copy a partno
concat(), [...a, ...b]join arraysno

Example

const list = ["a", "b", "c"];
list.push("d");
list.unshift("z");
console.log(list);
console.log(list.pop(), list.shift(), list);
const removed = list.splice(1, 1, "X", "Y");
console.log(removed, list);
console.log(list.slice(0, 2), list);

Output

[ 'z', 'a', 'b', 'c', 'd' ]
d z [ 'a', 'b', 'c' ]
[ 'b' ] [ 'a', 'X', 'Y', 'c' ]
[ 'a', 'X' ] [ 'a', 'X', 'Y', 'c' ]