Array Methods in JavaScript

What is an Array?

In JS, an array is an ordered list of values. You can think of it as a collection of items, stored in a linear format — like boxes arranged in a single row, each holding a piece of data.

In JavaScript, arrays are dynamic. This means:

  • You don’t need to define how many items it will hold in advance.

  • You can add or remove items anytime — the size of the array changes automatically.

Here's a simple example of an array:

let fruits = ["apple", "banana", "mango"];

In the example above, fruits is an array holding three items: "apple", "banana", and "mango".

Each item in an array is stored in a position called an index, and indexing starts from 0.

console.log(fruits[0]); // Output: apple
console.log(fruits[1]); // Output: banana

…………………………………………………………. Array Methods ………………………………………………………

1. push() – Add to the End

The push() method is used to add one or more items to the end of an array.

let fruits = ["apple", "banana"];
fruits.push("mango");

console.log(fruits); // Output: ["apple", "banana", "mango"]

👉 It updates the original array and also returns the new length of the array.

2. pop() – Remove from the End

The pop() method is used to remove the last item from the array.

let fruits = ["apple", "banana", "mango"];
fruits.pop();

console.log(fruits); // Output: ["apple", "banana"]

👉 It returns the item that was removed.

3. unshift() – Add to the Beginning

The unshift() method is used to add one or more items at the beginning of the array.

let fruits = ["banana", "mango"];
fruits.unshift("apple");

console.log(fruits); // Output: ["apple", "banana", "mango"]

👉 Like push(), it returns the new length of the array.

4. shift() – Remove from the Beginning

The shift() method is used to remove the first item from the array.

let fruits = ["apple", "banana", "mango"];
fruits.shift();

console.log(fruits); // Output: ["banana", "mango"]

👉 It returns the item that was removed.

5. includes() – Is the Item Present?

The includes() method is used to check whether a specific item exists in the array or not. It returns:

  • true if the item is found

  • false if the item is not found

✅ Useful for "yes or no" type questions.

let fruits = ["apple", "banana", "mango"];

console.log(fruits.includes("banana")); // Output: true
console.log(fruits.includes("grapes")); // Output: false

6. indexOf() – Where is the Item?

The indexOf() method tells you the index (position) of an item in the array.

  • If the item is found, it returns the index number (starting from 0).

  • If the item is not found, it returns -1.

let fruits = ["apple", "banana", "mango"];

console.log(fruits.indexOf("banana")); // Output: 1
console.log(fruits.indexOf("grapes")); // Output: -1

✅ Useful when you want to know the position of an item.

7.🔗 join() – Combine All Items into a String

The join() method is used to combine all elements of an array into a single string. By default, the items are joined using commas, but you can use any separator you like (such as a space, hyphen, or nothing at all).

It does not change the original array — it returns a new string.

🧪 Example 1: Using the default separator (comma)

let fruits = ["apple", "banana", "mango"];

let result = fruits.join();
console.log(result); // Output: "apple,banana,mango"

🧪 Example 2: Using a custom separator

let fruits = ["apple", "banana", "mango"];

let result = fruits.join(" - ");
console.log(result); // Output: "apple - banana - mango"

🧪 Example 3: Join without any separator

javascriptCopy codelet letters = ["H", "e", "l", "l", "o"];

let result = letters.join("");
console.log(result); // Output: "Hello"

✅ Use join() when you want to turn an array into a clean, readable string — like creating sentences, formatting data, or displaying items nicely on the screen.

8.slice() – Take a Piece (Without Changing the Original)

The slice() method is used to extract a portion of the array and return it as a new array.

  • It does not change the original array.

  • You provide the start index and end index (end index is not included).

let fruits = ["apple", "banana", "mango", "grapes"];

let result = fruits.slice(1, 3);
console.log(result); // Output: ["banana", "mango"]
console.log(fruits); // Output: ["apple", "banana", "mango", "grapes"]

🔸 It simply gives you a copy of a selected portion.

9. splice() – Add, Remove, or Replace (Changes Original Array)

The splice() method is used to change the contents of an array by:

  • Removing items

  • Adding new items

  • Replacing items

It does change the original array.

Syntax:

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

//✨ Meaning of each part:
//start → The index from where you want to start deleting or inserting.
//deleteCount → The number of items you want to remove starting from the start index.
//item1, item2, ... → Optional. These are the items you want to insert at the start position.

🧪 Example: Remove items

let fruits = ["apple", "banana", "mango", "grapes"];

fruits.splice(1, 2); // Removes 2 items from index 1
console.log(fruits); // Output: ["apple", "grapes"]

🧪 Example: Add items

let fruits = ["apple", "grapes"];

fruits.splice(1, 0, "banana", "mango");
console.log(fruits); // Output: ["apple", "banana", "mango", "grapes"]

🧪 Example: Replace items

let fruits = ["apple", "banana", "mango"];

fruits.splice(1, 1, "orange"); // Replace "banana" with "orange"
console.log(fruits); // Output: ["apple", "orange", "mango"]

🧹 Helpful Array Methods for Data Handling:

When working with dynamic data (like from APIs or scraping), it's important to check data types and convert them into arrays so that we can use array methods on them. Two useful methods are:

10. Array.isArray() – Check if it’s an Array

This method is used to check if a given value is an actual array. It returns true if the value is an array, otherwise false.

let data = ["apple", "banana"];
console.log(Array.isArray(data));  // Output: true

let name = "apple";
console.log(Array.isArray(name));  // Output: false

✅ Useful when you're not sure if the data you received is an array — especially in scraped or API data.

11. Array.from() – Convert to an Array

This method is used to convert array-like or iterable objects (like strings, NodeLists, Sets, etc.) into real arrays.

let name = "hello";
let letters = Array.from(name);

console.log(letters); // Output: ["h", "e", "l", "l", "o"]

Another example — converting a NodeList (which you often get when scraping HTML elements in the browser):

🧪 Example:

let items = document.querySelectorAll("p"); // This gives a NodeList
let arrayItems = Array.from(items); // Now it's a real array

console.log(Array.isArray(arrayItems)); // Output: true

Now, arrayItems is a real array, so you can loop over it, filter it, or map it just like any other array.

💡 Why is this useful?

If you're scraping or collecting multiple elements from the webpage (like all the buttons, headings, or paragraphs), converting them to an array helps you.

🧰 Powerful Array Methods in JavaScript

When working with arrays, JavaScript gives us some built-in methods that make it easier to handle and process data.

12. 🔍 filter() – Get Only What You Need

The filter() method is used to filter out items from an array based on a condition.

✅ It returns a new array with only the items that pass the test.

🧪 Example:

let numbers = [1, 2, 3, 4, 5];

let evenNumbers = numbers.filter(function(num) {
  return num % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4]

Think of it like: "Give me only the values that match my condition."

13. 🔁 forEach() – Just Loop Through

The forEach() method is used to loop through each item in the array and do something with it.

✅ It does not return anything, it just runs your code for each item.

🧪 Example:

let fruits = ["apple", "banana", "mango"];

fruits.forEach(function(fruit) {
  console.log(fruit);
});

Think of it like: "Go through each item and do this action."

14. 🧪 map() – Create a New Array by Changing Each Item

The map() method is used to transform every item in an array and return a new array.

✅ It’s great when you want to change or modify the values.

🧪 Example:

let numbers = [1, 2, 3];

let doubled = numbers.map(function(num) {
  return num * 2;
});
console.log(doubled); // Output: [2, 4, 6]

Think of it like: "Make a new array by updating each item."

15. ➕ reduce() – Get a Single Value from All Items

The reduce() method is used to combine all the values in an array into a single result.

The reduce() method is used when you want to take all values in an array and reduce them to a single result — like a total price, average, or sum.

ex- Total of a Shopping Cart

✅ It’s perfect for things like summing up numbers, calculating totals, etc.

🧪 Example: Shopping Cart Total

let cart = [100, 200, 150, 50];

let total = cart.reduce(function(acc, current) {
  return acc + current;
}, 0); // 0 is the starting value of acc

console.log(total); // Output: 500

💡 How It Works

reduce() takes two main things:

  • Accumulator → It stores the result of the previous calculation.

  • Current value → The current item in the array.

At first, the accumulator is set to the initial value you provide (like 0 for a sum).
Then, for each item, it updates the accumulator using the current value.

✅ Here's what happens step-by-step:

  • acc = 0, current = 100acc = 100

  • acc = 100, current = 200acc = 300

  • acc = 300, current = 150acc = 450

  • acc = 450, current = 50acc = 500 ✅ final result

Think of it like: "Keep combining values to get one final result."

13
Subscribe to my newsletter

Read articles from MRUTYUNJAYA SAHOO directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

MRUTYUNJAYA SAHOO
MRUTYUNJAYA SAHOO

Passionate about programming, I see its impact everywhere in the modern world. I believe that I will be a great addition to the team and organization. Making a positive impact through hands-on experience and continuous learning.