# Array Methods You Must Know in JavaScript

Arrays are one of the most powerful and commonly used data structures in JavaScript. If you understand array methods well, your code becomes cleaner, shorter, and more readable.

Let’s explore the most important array methods every beginner must know.

## 1\. `push()` and `pop()`

These methods work at the **end** of the array.

### ➤ `push()` – Add element to the end

```plaintext
let numbers = [1, 2, 3];

numbers.push(4);

console.log(numbers);
```

✅ Before: `[1, 2, 3]`  
✅ After: `[1, 2, 3, 4]`

### ➤ `pop()` – Remove element from the end

```plaintext
let numbers = [1, 2, 3];

numbers.pop();

console.log(numbers);
```

✅ Before: `[1, 2, 3]`  
✅ After: `[1, 2]`

## 2\. `shift()` and `unshift()`

These methods work at the **start** of the array.

### ➤ `unshift()` – Add element to the beginning

```plaintext
let numbers = [2, 3];

numbers.unshift(1);

console.log(numbers);
```

✅ Before: `[2, 3]`  
✅ After: `[1, 2, 3]`

### ➤ `shift()` – Remove element from the beginning

```plaintext
let numbers = [1, 2, 3];

numbers.shift();

console.log(numbers);
```

✅ Before: `[1, 2, 3]`  
✅ After: `[2, 3]`

## 3\. `map()` – Transform Each Element

The JavaScript `map()` **method is used to transform each element of an array and return a new array with the results, leaving the original array unchanged**

### Example: Double each number

```plaintext
let numbers = [1, 2, 3, 4];

let doubled = numbers.map(function(num) {
  return num * 2;
});

console.log(doubled);
```

✅ Before: `[1, 2, 3, 4]`  
✅ After: `[2, 4, 6, 8]`

* * *

## 🆚 Traditional Loop vs `map()`

### Traditional Loop

```plaintext
let result = [];

for (let i = 0; i < numbers.length; i++) {
  result.push(numbers[i] * 2);
}
```

### Using `map()`

```plaintext
let result = numbers.map(num => num * 2);
```

✨ Cleaner  
✨ Shorter  
✨ More readable

## How `map()` Works (Flow)

![](https://cdn.hashnode.com/uploads/covers/69552b7d65d87f2ddc0ba76b/b2da936c-b26b-4659-8268-ceb5f3c69fcc.png align="center")

**Process:**

1.  Takes first element
    
2.  Applies function
    
3.  Stores result
    
4.  Repeats for every element
    
5.  Returns new array
    

Here is a step-by-step breakdown of the internal process:

*   **Initialization**: When `map()` is called on an array, the JavaScript engine first creates a new, empty array. This new array will have the same length as the original array and serves as the container for the transformed elements.
    
*   **Iteration**: The engine then iterates through each element of the original array in order, similar to how a `for` loop would.
    
*   **Callback Execution**: For each element that actually exists in the array (it skips empty slots in sparse arrays), the engine calls the provided callback function. This callback function automatically receives up to three arguments:
    
    *   The `currentValue` of the array element being processed.
        
    *   The `index` of the current element.
        
    *   The `array` object that `map()` was called on.
        
*   **Transformation and Assignment**: The code inside the callback function executes, performs a transformation, and returns a new value. This returned value is then added to the corresponding index of the new array being built.
    
*   **Return Value**: Once the loop has processed all elements in the original array, the `map()` method returns the newly created array containing all the transformed values. 
    

## 4\. `filter()` – Select Elements

`filter()` returns a new array with elements that match a condition.

### Example: Get numbers greater than 2

```plaintext
let numbers = [1, 2, 3, 4];

let result = numbers.filter(function(num) {
  return num > 2;
});

console.log(result);
```

✅ Before: `[1, 2, 3, 4]`  
✅ After: `[3, 4]`

## How `filter()` Works

![](https://cdn.hashnode.com/uploads/covers/69552b7d65d87f2ddc0ba76b/bf04a8ad-2c56-4bd4-9a42-114dbde0af17.png align="center")

The internal implementation of `Array.prototype.filter()` is similar to a manual `for` loop, but managed by the JavaScript engine for efficiency and standardized behavior. Here are the key steps: 

*   **Initialization**: When `filter()` is called, the JavaScript engine first creates a new, empty array to hold the filtered results. This new array ensures immutability (the original array is not modified).
    
*   **Iteration**: The engine then iterates through the elements of the original array in ascending order. The iteration is designed to skip empty slots in sparse arrays.
    
*   **Callback Execution**: For each element, the engine calls the provided **callback function**, passing the current `element`, its `index`, and the original `array` as arguments.
    
*   **Condition Check**: The callback function contains the filtering logic and must return a boolean (or truthy/falsy) value.
    
    *   If the callback returns `true` (or a truthy value), the current element is added (pushed) into the new array.
        
    *   If the callback returns `false` (or a falsy value), the element is skipped and not included in the new array.
        
*   **Return Value**: After iterating through all elements in the original array, the `filter()` method returns the newly constructed array containing only the elements that passed the test.
    

Each element:

*   If condition is **true** → keep it
    
*   If **false** → discard it
    

## 5\. `reduce()` – Accumulate Values

`reduce()` is used to combine all elements into a single value.

Let’s keep it beginner-friendly.

### Example: Find total sum

```plaintext
let numbers = [1, 2, 3, 4];

let total = numbers.reduce(function(accumulator, current) {
  return accumulator + current;
}, 0);

console.log(total);
```

✅ Output: `10`

## 🧠 What’s Happening?

*   Start with `0`
    
*   Add `1` → 1
    
*   Add `2` → 3
    
*   Add `3` → 6
    
*   Add `4` → 10
    

## How `reduce()` Works

![](https://cdn.hashnode.com/uploads/covers/69552b7d65d87f2ddc0ba76b/abbbc0de-54f1-40b9-910d-5cfab71ca5dc.png align="center")

**Step-by-Step Internal Mechanism**

Under the hood, the `reduce()` function can be conceptualized as a loop with internal management of the accumulator and current position. 

1.  **Initialization**: The process begins with setting the initial value of the **accumulator**.
    
    *   If an `initialValue` is provided as the second argument to `reduce()`, the accumulator starts with that value.
        
    *   If no `initialValue` is provided, the accumulator is automatically initialized to the first element of the array, and the iteration starts from the second element.
        
2.  **Iteration**: The JavaScript engine iterates through the array elements in order. For each element (the `currentValue`), it invokes the callback function with the following arguments:
    
    *   `accumulator`: The value returned from the previous callback invocation (or the initial value on the first run).
        
    *   `currentValue`: The value of the current array element being processed.
        
    *   `currentIndex` (optional): The index of the current element.
        
    *   `array` (optional): The original array `reduce()` was called upon.
        
3.  **Accumulation**: The callback function performs an operation and returns a new value. This returned value immediately replaces the accumulator's value for the next iteration.
    
4.  **Completion**: This process continues until all elements in the array have been processed.
    
5.  **Final Result**: Once the loop finishes, the final, single value held by the accumulator is returned by the `reduce()` method. 
    

Think of it as:

> Keep updating one value until the array ends.

## 6\. `forEach()` – Loop Through Array

`forEach()` runs a function on every element.

```plaintext
let numbers = [1, 2, 3];

numbers.forEach(function(num) {
  console.log(num);
});
```

✔ Does not return a new array  
✔ Used when you just want to perform an action

## 🧪 Assignment for You

Try this in your browser console:

```plaintext
let numbers = [5, 8, 12, 15, 3];

// 1. Double each number
let doubled = numbers.map(num => num * 2);

// 2. Get numbers greater than 10
let greaterThanTen = numbers.filter(num => num > 10);

// 3. Find total sum
let total = numbers.reduce((acc, num) => acc + num, 0);

console.log(doubled);
console.log(greaterThanTen);
console.log(total);
```

## 🎯 Final Thoughts

If you master:

*   `push()` / `pop()`
    
*   `shift()` / `unshift()`
    
*   `map()`
    
*   `filter()`
    
*   `reduce()`
    
*   `forEach()`
    

You’ll write cleaner JavaScript than 70% of beginners.

Don’t just read, open your console and experiment. Break things. Modify examples. That’s how real learning happens.
