- Home
- /
- Tutorials
- /
- DSA Tutorial
- /
- Arrays in JavaScript for DSA
Arrays
Arrays in JavaScript for DSA
Almost every DSA problem starts with an array. Knowing which of its methods are cheap and which quietly cost O(n) is most of what separates a fast solution from a slow one.
What an array actually is
A JavaScript array is an indexed list. Reading items[5] does not search - it jumps straight there. That is why index access is O(1) however long the array is.
Everything else follows from that one fact.
The costs you have to know
Cheap and expensive operations
javascript
const items = [10, 20, 30, 40, 50]
// O(1) — the end of the array is right there.
items[2] // read by index
items.push(60) // add to the end
items.pop() // remove from the end
// O(n) — everything after the change shifts along.
items.shift() // remove from the front
items.unshift(5) // add to the front
items.splice(2, 0, 25) // insert in the middle
// O(n) — has to look at every element.
items.indexOf(30)
items.includes(30)
items.find((n) => n > 25)