JavaScript Arrays & Objects

Almost every interesting program moves data around, and in JavaScript that data lives in two structures: arrays (ordered lists) and objects (named properties). Master their methods and you can express complex logic in a few lines.

Arrays

JavaScript
const scores = [88, 45, 72, 95];
scores[0];            // 88   — indexes start at 0
scores.length;        // 4
scores[scores.length - 1];  // 95 — last item

Adding/removing — note which ones mutate the original:

Method Does Mutates?
push(x) / pop() add/remove at end yes
unshift(x) / shift() add/remove at start yes
splice(i, n) remove/insert at index i yes
slice(a, b) copy portion [a, b) no
[...arr] shallow copy —

The trio map → filter → reduce chains beautifully because each returns a new array/value:

JavaScript
const expensiveNames = items
  .filter((i) => i.price > 100)   // pick
  .map((i) => i.name)             // shape
  .sort();                        // order

Others worth knowing: .find(fn) / .findIndex(fn) (first match), .some(fn) / .every(fn) (boolean checks), .includes(x), .flat(), .join(sep).

sort() — the classic trap

With no argument, sort() converts elements to strings and sorts lexicographically:

Always pass (a, b) => a - b for numbers. It mutates in place, hence the spread first when you need the original preserved.

Objects

JavaScript
const book = {
  title: "Muna Madan",
  author: "Devkota",
  year: 1936,
};

book.title;             // dot access
book["year"];           // bracket access — needed for dynamic keys
book.rating = 4.8;      // add
delete book.year;       // remove

Iterate with Object.keys/values/entries:

Copying: shallow vs deep

JavaScript
const original = { a: { b: 1 } };

const shallow = { ...original };       // nested objects still SHARED
shallow.a.b = 999;
original.a.b;                          // 999 — surprise!

const deep = structuredClone(original); // true deep copy, handles Dates etc.

Knowledge Check

4 questions — test your understanding

1

What is the difference between slice and splice?

2

What does [1, 10, 2].sort() return?

3

What does Object.entries({a: 1}) return?

4

Which produces a true DEEP copy?