DEV Community

Raj Mahto
Raj Mahto

Posted on

A Beginner-Friendly Guide to JavaScript Arrays (with Examples)

Arrays in JavaScript are like tiny storage shelves where each item has a number tag (index). They let us store multiple values together and work with them easily.

What Are Arrays?

An array is a collection of elements.
Although it's recommended to store values of the same data type, JavaScript arrays can actually hold any type.

Arrays are represented using square brackets [], like this:

let arr = [4, 8, 7, -1, 0, 4, 9];
Enter fullscreen mode Exit fullscreen mode

Indexing in Arrays
Every element has a reference called an index.
Indexing starts at 0 and increases by 1 for each element.

So for an array of n elements, the valid index range is:
0 to n-1

Examples:

console.log(arr[2]);   // 7
console.log(arr[25]);  // undefined
Enter fullscreen mode Exit fullscreen mode

Array Length
Every array has a built-in property .length, which is simply:
->last index + 1

console.log(arr.length); // 7
Enter fullscreen mode Exit fullscreen mode

Arrays Are Mutable
Arrays in JavaScript are mutable — meaning many functions can change the original array.
Let’s look at the common methods.

Array Methods You Must Know

1️⃣ push()
Adds elements at the end and returns the new length.

let arr = [1, 2, 3];
arr.push(4, 5);

console.log(arr); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

2️⃣ pop()
Removes the last element and returns it.

let arr = [1, 2, 3, 4, 5];
arr.pop();

console.log(arr); // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

3️⃣ unshift()
Adds elements at the beginning and returns new length.

let arr = [1, 2, 3];
arr.unshift(4, 5);

console.log(arr); // [4, 5, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

4️⃣ shift()
Removes the first element and returns it.

let arr = [1, 2, 3];
arr.shift();


console.log(arr); // [2, 3]
Enter fullscreen mode Exit fullscreen mode

5️⃣ splice()

A powerful method used to add, remove, or replace elements.
splice(startIndex, deleteCount, ...itemsToInsert)

Examples:

let arr = [5, 6, 7, 8, 9, 10, 11, 12];

arr.splice(3);              // delete all from index 3
arr.splice(3, 1);           // delete only element at index 3
arr.splice(3, 2, "raj", "shekhar", "john"); // replace 2 items
Enter fullscreen mode Exit fullscreen mode

Mini Task — Array Manipulation Practice

Given:

let friends = ["sheldon", "rachel", "ross", "chandler", "monica", "penny"];
Enter fullscreen mode Exit fullscreen mode

1️⃣ Remove "sheldon" and add "pheobe"

friends.shift();
friends.unshift("pheobe");
Enter fullscreen mode Exit fullscreen mode

2️⃣ Remove "penny" and add "joey"

friends.pop();
friends.push("joey");
Enter fullscreen mode Exit fullscreen mode

3️⃣ Add "emma" between "rachel" and "ross"

friends.splice(2, 0, "emma");
Enter fullscreen mode Exit fullscreen mode

Top comments (0)