An array is a special object for storing a collection of data (can be any type: numbers, strings, objects, or even arrays). It's similar to a list in Python.
Always use the literal []—faster and more readable. Avoid new Array(length) if you want to fill it manually, as it can create a sparse array (empty index).
Access & Modify Elements
- Access using index (starting from 0).
- Modify: Directly assign.
JS arrays are dynamic—you can add/remove elements at any time. But be careful with delete arr[0], which creates a hole (index undefined), not an array shift.
Mutating Method (Change Original Array)
This is a method that changes the array directly—be careful when passing arrays to functions.
push(item)add to endarr.push('d')→['a','b','c','d']pop()delete & return at endarr.pop()→'d'now arr['a', 'b', 'c']unshift()add to frontarr.unshift('z')→['z','a','b','c']shift()delete & return frontarr.shift() → 'z', arr now['a', 'b', 'c']splice(start, deleteCount, ...items)delete/add in specific indexarr.splice(1, 1, 'X')→['a', 'X', 'c'](remove 1 element starting from idx 1)
push/pop is fast (O(1)), but unshift/shift is slow (O(n)) because it has to shift all elements. Use splice for intermediate operations—flexible but expensive performance.
Non-Mutating Method (Create a New Array)
Great for functional programming—native arrays are safe.
slice(start, end)cut sub-arrayarr.slice(1, 3)→['b', 'c'](end exclusive)concat(...arrays)join arrayarr.concat(['d', 'e'])→['a', 'b', 'c', 'd', 'e']toString()/join(sep)convert to stringarr.join(', ')→'a, b, c'
Always use the slice or spread operator (...) for copying: const copy = [...arr];. Avoid arr.slice() if you need a deep copy (use JSON.parse(JSON.stringify(arr)) for nested ones).