JavaScript Arrays and Their Methods Explained

What is an Array?

An array is a special variable that can hold multiple values in an ordered list. Arrays are used when you want to store collections of data such as a list of names, numbers, or objects in a single variable.

Example of an array:

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

What are Array Methods?

Array methods are built-in functions that allow you to perform common tasks on arrays, like adding or removing elements, iterating, searching, transforming, and more. They make working with arrays easy and efficient.

Example of a method used on an array:

fruits.push("Orange"); // Adds "Orange" to the end of the fruits array

Main Array Methods with Examples and Use Cases

1. push()

Definition: Adds one or more elements to the end of an array and returns the new length.

Example:

const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]

Use Case: Use push to add new items at the end, like adding a new message to a chat array.

2. pop()

Definition: Removes the last element from the array and returns it.

Example:

const arr = [1, 2, 3];
const last = arr.pop();
console.log(last); // 3
console.log(arr); // [1, 2]

Use Case: Use pop to remove the most recent item, such as undoing the last action in a list.

3. shift()

Definition: Removes the first element from the array and returns it.

Example:

const arr = ["a", "b", "c"];
const first = arr.shift();
console.log(first); // "a"
console.log(arr); // ["b", "c"]

Use Case: Use shift to remove the oldest item, like processing a queue.

4. unshift()

Definition: Adds one or more elements to the beginning of an array and returns the new length.

Example:

const arr = [2, 3];
arr.unshift(1);
console.log(arr); // [1, 2, 3]

Use Case: Use unshift to add urgent items to the front, like adding priority tasks to a list.

5. splice()

Definition: Adds or removes elements at a specific index in the array.

Syntax: array.splice(start, deleteCount, item1, item2, ...)

Example:

const arr = ["a", "b", "c", "d"];
arr.splice(1, 2, "x", "y"); 
console.log(arr); // ["a", "x", "y", "d"]

Use Case: Use splice to replace, add or remove items anywhere in the array, such as editing a list of items dynamically.

6. slice()

Definition: Returns a shallow copy of a portion of an array without modifying the original.

Syntax: array.slice(start, end)

Example:

const arr = [1, 2, 3, 4, 5];
const part = arr.slice(1, 4);
console.log(part); // [2, 3, 4]

Use Case: Use slice to get sublists, like showing a page of items in pagination.

7. concat()

Definition: Merges two or more arrays and returns a new array.

Example:

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2);
console.log(combined); // [1, 2, 3, 4]

Use Case: Use concat to join multiple lists, like combining multiple user inputs.

8. indexOf()

Definition: Returns the first index of a specified element or -1 if not found.

Example:

const arr = ["apple", "banana", "cherry"];
console.log(arr.indexOf("banana")); // 1
console.log(arr.indexOf("orange")); // -1

Use Case: Use indexOf to find the position of an item in a list.

9. includes()

Definition: Returns true if an array contains a specified element, otherwise false.

Example:

const arr = [10, 20, 30];
console.log(arr.includes(20)); // true
console.log(arr.includes(40)); // false

Use Case: Use includes to check if an item exists before performing actions.

10. forEach()

Definition: Executes a provided function once for each array element.

Example:

const arr = ["a", "b", "c"];
arr.forEach(item => console.log(item));
// Output: a b c

Use Case: Use forEach to perform actions like printing or updating every element.

11. map()

Definition: Creates a new array with the results of calling a function on every element.

Example:

const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6]

Use Case: Use map to transform data, like doubling numbers or formatting strings.

12. filter()

Definition: Creates a new array with all elements that pass a test.

Example:

const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]

Use Case: Use filter to select specific elements, such as filtering active users from a list.

13. reduce()

Definition: Reduces the array to a single value by executing a reducer function.

Example:

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((total, n) => total + n, 0);
console.log(sum); // 10

Use Case: Use reduce to sum values, calculate averages, or combine items into one result.

14. find()

Definition: Returns the first element that satisfies a testing function.

Example:

const users = [{id:1, name:"A"}, {id:2, name:"B"}];
const user = users.find(u => u.id === 2);
console.log(user); // {id: 2, name: "B"}

Use Case: Use find to locate a single item, such as searching a user by ID.

15. findIndex()

Definition: Returns the index of the first element that satisfies a testing function, or -1 if none found.

Example:

const nums = [10, 20, 30];
const idx = nums.findIndex(n => n > 15);
console.log(idx); // 1

Use Case: Use findIndex to find position for updating or deleting items.

16. sort()

Definition: Sorts the elements of an array in place and returns it.

Example:

const arr = [3, 1, 4, 2];
arr.sort();
console.log(arr); // [1, 2, 3, 4]

Use Case: Use sort to order lists alphabetically or numerically.

17. reverse()

Definition: Reverses the order of the elements in an array.

Example:

const arr = [1, 2, 3];
arr.reverse();
console.log(arr); // [3, 2, 1]

Use Case: Use reverse to display items in reverse order, like showing recent messages first.

b cz

18. join()

Definition: Joins all elements into a string, separated by a specified separator.

Example:

const arr = ["Hello", "World"];
const str = arr.join(" ");
console.log(str); // "Hello World"

Use Case: Use join to create CSV strings or formatted text from array data.

18. Most Important methods

Know more in Detail

References

For detailed documentation, visit MDN Web Docs: Array