What is an Array?
An array is an ordered, zero-indexed collection of values. In JavaScript arrays are objects with a special length property, so a single array can hold values of any type mixed together — numbers, strings, objects, even other arrays.
const fruits = ["apple", "banana", "cherry"];
const mixed = [1, "two", true, null, { id: 4 }];
const empty = [];
console.log(fruits.length); // 3Indexing
Elements are accessed by their position, starting at 0. The last element is at index length - 1. Reading an index that does not exist returns undefined rather than throwing an error.
const colors = ["red", "green", "blue"];
console.log(colors[0]); // "red"
console.log(colors[colors.length - 1]); // "blue"
console.log(colors[10]); // undefined
console.log(colors.at(-1)); // "blue" (negative indexing)Mutating Arrays
Arrays are mutable. push and pop add/remove at the end; unshift and shift add/remove at the front. splice inserts or removes anywhere. These methods change the original array in place.
const stack = [1, 2, 3];
stack.push(4); // [1, 2, 3, 4] -> returns new length 4
stack.pop(); // [1, 2, 3] -> returns 3
stack.unshift(0); // [0, 1, 2, 3]
stack.shift(); // [1, 2, 3] -> returns 0
stack.splice(1, 1, "x", "y"); // remove 1 at idx 1, insert x,y -> [1, "x", "y", 3]Key Points
Arrays are zero-indexed; the first element is index 0.
length is always the highest index + 1, and setting length can truncate the array.
push/pop/shift/unshift/splice mutate the array and are common causes of bugs when the array is shared.
slice(start, end) returns a shallow copy and does NOT mutate; splice does mutate.
Use Array.isArray(x) to reliably test whether a value is an array (typeof [] is "object").