Arrays in Javascript

What is a JavaScript Array?

In JavaScript, an array is actually just a special type of Object. It is dynamic, resizable, and can hold a mix of completely different data types at the same time.

  • No Fixed Size: You do not need to declare how many elements it will hold. It grows and shrinks automatically.
  • Mixed Types: You can put a string, a number, an object, and another array all inside the same array.
  • Reference Type: Like objects, arrays are stored on the heap and passed by reference.
// A valid JavaScript array
const chaoticArray = [42, "Hello", { name: "John" }, true, [1, 2, 3]];

Creating and Accessing Arrays

You create arrays using the bracket [] syntax

const fruits = ["Apple", "Banana", "Cherry"];

console.log(fruits[0]); // "Apple"
console.log(fruits.length); // 3

// Modifying an element
fruits[1] = "Mango";

1. Adding New Elements

You can add elements to the beginning, middle, or end of an array.

  • To the End: push(item)
  • To the Beginning: unshift(item)
  • To the Middle:splice(startIndex, deleteCount, itemToAdd)
    • Note: splice is a multi-tool. If deleteCount is 0, it just inserts the item.
const letters = ['a', 'b'];

letters.push('c');       // Adds to end: ['a', 'b', 'c']
letters.unshift('z');    // Adds to start: ['z', 'a', 'b', 'c']
letters.splice(2, 0, 'x'); // Inserts at index 2: ['z', 'a', 'x', 'b', 'c']

The React Way (Immutability): Instead of modifying the array, use the Spread Operator (...) to create a new one with the added elements. const newLetters = [...letters, 'd'];

2. Finding Elements

How you find an element depends on whether your array holds simple values (primitives) or complex objects (reference types).

For Primitives (Strings, Numbers):

  • indexOf(item): Returns the index number. Returns -1 if not found.
  • includes(item): Returns true or false. (Very common in if-statements).

For Objects (Reference Types):

  • find(): Takes a callback function and returns the first actual item that matches the condition.
  • findIndex(): Returns the index of the first matching item.

// Finding Primitives
const nums = [10, 20, 30];
console.log(nums.includes(20)); // true
console.log(nums.indexOf(30));  // 2

// Finding Objects
const users = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
const foundUser = users.find(user => user.name === 'Bob');
console.log(foundUser); // { id: 2, name: 'Bob' }

3. Removing Elements

Similar to adding, you can remove from the start, middle, or end. These methods permanently alter the original array.

  • From the End: pop()
  • From the Beginning: shift()
  • From the Middle: splice(startIndex, deleteCount)
const colors = ['red', 'green', 'blue', 'yellow'];

colors.pop();             // Removes 'yellow': ['red', 'green', 'blue']
colors.shift();           // Removes 'red': ['green', 'blue']
colors.splice(0, 1);      // Starts at index 0, deletes 1 item: ['blue']

The React Way: Never use pop or splice in React state. Always use filter() to return a new array that excludes the item you want to remove.

4. Emptying an array

Emptying an array in JavaScript seems simple, but there is a major “gotcha” depending on whether you want to delete the array entirely or just clear out its contents.

Here are the standard ways to empty an array, from most common to least common:

1. Reassigning to a New Array (The Safest Way)

If you declared your array with let, you can simply assign it to a brand-new, empty array [].

  • How it works: It abandons the old array (leaving it for Garbage Collection) and creates a fresh one in memory.
  • The “Gotcha”: If another variable is still pointing to the original array, that other variable will not be emptied.
let numbers = [1, 2, 3];
let anotherPointer = numbers; // Both point to the same data

numbers = []; // 'numbers' gets a brand new empty array

console.log(numbers);       // []
console.log(anotherPointer); // [1, 2, 3] (Still has the old data!)

2. Setting .length = 0 (The Best Way)

This is the most efficient and bulletproof way to empty an array. Because the .length property in JavaScript is read/write, setting it to 0 literally deletes all the items inside the existing array.

  • How it works: It modifies the original array in memory.
  • Why it’s great: It works even if you used const, and it empties the array for any other variables that are pointing to it.
const fruits = ['apple', 'banana', 'orange'];
const fruitPointer = fruits;

fruits.length = 0; // Truncates the original array

console.log(fruits);       // []
console.log(fruitPointer); // [] (Also empty, because it's the same memory!)

3. Using .splice() (The Alternative)

You can use the splice() method to start at index 0 and delete every item up to the array’s length. This behaves exactly like setting .length = 0 (it mutates the original array), but it is a bit more verbose.

const colors = ['red', 'green', 'blue'];

colors.splice(0, colors.length);

console.log(colors); // []

4. The Loop Method (Not Recommended)

You could use a loop to .pop() items off the end until it’s empty, but this is incredibly slow and completely unnecessary in modern JavaScript.

const items = [1, 2, 3];
while (items.length > 0) {
  items.pop();
}

Summary: Which one should you use?

MethodMutates Original?Works with const?Best For…
array.length = 0YesYesClearing data while keeping the memory reference intact.
array = []No (creates new)NoCompletely resetting a state variable (common in React).

5. Splitting Arrays

To extract a section of an array into a new array, use the slice() method.

  • slice(startIndex, endIndex)
  • Key Detail: It includes the startIndex, but goes up to (and does not include) the endIndex.
  • Key Detail 2: slice() does not modify the original array. It returns a shallow copy.
const animals = ['Dog', 'Cat', 'Bird', 'Fish', 'Lion'];

// Grab elements from index 1 up to (but not including) index 4
const pets = animals.slice(1, 4); 

console.log(pets);    // ['Cat', 'Bird', 'Fish']
console.log(animals); // Original remains unchanged!

6. Combining Arrays

To merge two or more arrays together, you can use the concat() method or the modern spread operator. Both return a brand-new array and leave the originals untouched.

  • The Traditional Way: array1.concat(array2)
  • The Modern/React Way: [...array1, ...array2]
const array1 = [1, 2];
const array2 = [3, 4];

// Using concat()
const combined = array1.concat(array2); // [1, 2, 3, 4]

// Using Spread Operator (Cleaner and more flexible)
const modernCombined = [...array1, ...array2, 5, 6]; // [1, 2, 3, 4, 5, 6]
Table of Contents