arrayjavascript

Array in JavaScript

1 min read
0 views






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.

JavaScript
// Literal (most common)const fruits = ['apple', 'banana', 'cherry'];// Constructor (rarely used, but can be used)const nums = new Array(1, 2, 3);// Empty arrayconst empty = [];

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).
JavaScript
const arr = ['a', 'b', 'c'];console.log(arr[0]); // 'a'console.log(arr[arr.length - 1]); // 'c' (last item)
  • Modify: Directly assign.
JavaScript
arr[1] = 'B'; // arr now ['a', 'B', 'c']

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 end arr.push('d')['a','b','c','d']
  • pop() delete & return at end arr.pop()'d' now arr ['a', 'b', 'c']
  • unshift() add to front arr.unshift('z')['z','a','b','c']
  • shift() delete & return front arr.shift() → 'z', arr now ['a', 'b', 'c']
  • splice(start, deleteCount, ...items) delete/add in specific index arr.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-array arr.slice(1, 3)['b', 'c'] (end exclusive)
  • concat(...arrays) join array arr.concat(['d', 'e'])['a', 'b', 'c', 'd', 'e']
  • toString() / join(sep) convert to string arr.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).

0
Back to notes