JavaScript Arrays

Learn how to store lists of data, add and remove items, copy safely, and use modern array features without confusing jargon.

1. What is an Array?

An array is simply an ordered list of items. Instead of creating 5 different variables for 5 student names, you can put all of them into a single array.

💡 Think of it like a numbered shelf

Imagine a shelf with numbered slots starting from 0. The first item sits at slot 0, the second at 1, and so on. In JavaScript, you can put anything in these slots — numbers, words, true/false, or even another list!

// Creating an array with square brackets []
const fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]); // "Apple" (First item)
console.log(fruits[1]); // "Banana" (Second item)
console.log(fruits.length); // 3 (Total count of items)

// Checking if something is an array:
console.log(Array.isArray(fruits)); // true
Output
Apple
Banana
3
true

2. Adding & Removing Items

JavaScript gives you 4 simple commands to add or remove items from the start or end of your list:

Working with the End (Fast ⚡)

Adding or removing at the end is super quick because no other items have to move.

  • push(item): Adds an item to the very end
  • pop(): Removes the last item and gives it to you
const list = ["A", "B"];
list.push("C"); // ["A", "B", "C"]
const last = list.pop(); // removes "C"
console.log(list); // ["A", "B"]

Working with the Front (Slower ⚠️)

Adding or removing at the start shifts every other item by 1 position.

  • unshift(item): Adds an item to the very front
  • shift(): Removes the first item and gives it to you
const list = ["B", "C"];
list.unshift("A"); // ["A", "B", "C"]
const first = list.shift(); // removes "A"
console.log(list); // ["B", "C"]

Easier way to grab the last item: .at(-1)

Instead of writing messy code like arr[arr.length - 1], modern JavaScript lets you use negative numbers with .at():

const scores = [50, 75, 90, 99];
console.log(scores.at(-1)); // 99 (Last item)
console.log(scores.at(-2)); // 90 (Second from last)

3. `slice()` vs `splice()` (Copying vs Modifying)

These two method names look almost the same, but they do completely different things:

`slice()` = Cut out a piece (Safe ✅)

Takes a photo of a section of your array and gives you a brand new list.

  • Does NOT change your original array
  • slice(start, end) stops before end
const original = [1, 2, 3, 4, 5];
const piece = original.slice(1, 4); // slots 1, 2, 3

console.log(piece);    // [2, 3, 4]
console.log(original); // [1, 2, 3, 4, 5] (Untouched!)

`splice()` = Cut & Glue in place (Modifies ⚠️)

Directly removes, deletes, or injects items into the original array.

  • Modifies the original list directly
  • splice(start, howManyToDelete, ...itemsToAdd)
const original = [1, 2, 3, 4, 5];
const removed = original.splice(1, 2, 99); 
// at index 1, remove 2 items, insert 99

console.log(removed);  // [2, 3]
console.log(original); // [1, 99, 4, 5] (Changed!)

4. Modern Non-Destructive Array Methods

In modern JavaScript (and especially React), you usually want to avoid changing original arrays. Modern JavaScript added safe versions of sorting and reversing that always return a fresh new copy:

Old Way (Modifies Original ⚠️) New Safe Way (Returns New Copy ✅) What it does
arr.sort() arr.toSorted() Sorts items into a new list
arr.reverse() arr.toReversed() Reverses items into a new list
arr.splice(...) arr.toSpliced(...) Removes/adds items into a new list
arr[i] = "new" arr.with(i, "new") Replaces 1 item and gives you a new list
const nums = [3, 1, 2];

// Safe sorting without messing up the original list:
const sorted = nums.toSorted((a, b) => a - b);
console.log("New sorted list:", sorted); // [1, 2, 3]
console.log("Original list:", nums);      // [3, 1, 2] (Protected!)

5. Unpacking Arrays & The Spread Operator (`...`)

You can easily extract items into individual variables or combine multiple lists together:

// 1. Destructuring: Pulling items out by position
const rgb = [255, 128, 0];
const [red, green, blue] = rgb;
console.log(red, green, blue); // 255 128 0

// Grab the first item, collect the rest with ...rest:
const users = ["Anshuman", "Priya", "Rahul", "Sara"];
const [leader, ...team] = users;
console.log("Leader:", leader); // "Anshuman"
console.log("Team:", team);     // ["Priya", "Rahul", "Sara"]

// 2. Spread (...): Merging lists together
const vegetables = ["Carrot", "Potato"];
const fruitsList = ["Apple", "Orange"];
const groceryCart = [...vegetables, ...fruitsList, "Milk"];

console.log(groceryCart); // ["Carrot", "Potato", "Apple", "Orange", "Milk"]
Output
255 128 0
Leader: Anshuman
Team: [ 'Priya', 'Rahul', 'Sara' ]
[ 'Carrot', 'Potato', 'Apple', 'Orange', 'Milk' ]

6. Copying Lists: Shallow vs Deep Copies

When you copy a list using [...arr] or arr.slice(), simple values (like numbers and strings) are cloned. But if your list contains objects, both lists will still share the same objects!

⚠️ The Shared Object Trap

If you have [{ task: "Study" }] and copy it with [...list], changing copy[0].task = "Done" also changes the original list. To make a 100% independent copy, use structuredClone(list).

const original = [{ name: "Alex", score: 80 }];

// ❌ Shallow Copy: Object inside is shared
const shallowCopy = [...original];
shallowCopy[0].score = 99;
console.log(original[0].score); // 99 (Original got changed accidentally!)

// ✅ Deep Copy: Completely independent clone
const safeCopy = structuredClone(original);
safeCopy[0].name = "Rahul";
console.log(original[0].name); // "Alex" (Original is 100% safe!)
Output
99
Alex

7. Quick Summary of Common Array Methods

Method What it does Changes Original?
push() / pop() Add / remove an item at the end Yes (Modifies)
unshift() / shift() Add / remove an item at the start Yes (Modifies)
slice(start, end) Copies a section of the list No (Safe)
splice(start, count) Deletes or replaces items in place Yes (Modifies)
[...a, ...b] Merges lists into a new one No (Safe)
toSorted() Returns a sorted new list No (Safe)

8. Arrays Interview Deck

Test your knowledge on array mutations, default sorting behavior, return values of push/pop, and shallow copying:

🎯 Arrays Interview Deck
Question 1 of 5
⭐ Easy • push() Return Value Array Methods
const fruits = ["apple", "banana"];
const result = fruits.push("cherry");

console.log(result);
What will be logged to the console?
A) ["apple", "banana", "cherry"]
B) 3
C) "cherry"
D) undefined
⭐ Easy • slice() Immutability slice vs splice
const nums = [10, 20, 30, 40, 50];
const sub = nums.slice(1, 3);
sub.push(99);

console.log(nums.length);
What is the length of original array nums?
A) 5
B) 6
C) 3
D) 2
⚡ Medium • Default Sort Pitfall Array.prototype.sort
const scores = [10, 5, 40, 25];
scores.sort();

console.log(scores);
What is the output of scores.sort()?
A) [5, 10, 25, 40]
B) [40, 25, 10, 5]
C) [10, 25, 40, 5]
D) [5, 40, 25, 10]
⚡ Medium • Shallow Copy Reference Spread & References
const a = [{ x: 1 }];
const b = [...a];
b[0].x = 99;

console.log(a[0].x);
What will be logged to the console?
A) 1
B) 99
C) undefined
D) TypeError
⭐ Easy • Type Checking Arrays typeof vs Array.isArray
const list = [1, 2, 3];

console.log(typeof list, Array.isArray(list));
What will be printed to the console?
A) "array" true
B) "object" true
C) "object" false
D) "list" true

9. Practice Challenge

🎯 Coding Challenge: Array Operations & Safe Cloning

1. Find the first product with available: true using .find().
2. Check if every product is available using .every().
3. Use structuredClone() to make an independent copy, change the laptop's availability to true in the copy, and verify the original remains false.

Your output will appear here.