2. Building JavaScript Array Methods from Scratch in 2024 - Easy tutorial for beginners.
Tags: javascript, beginners, tutorial, learning
Published: 2024-06-19 08:05:48

Video version link: https://www.youtube.com/watch?v=3DE4-o23tPc

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fn7974atr8i9m06qr2r5.png)
Continuing our series of building javaScript method from Scratch for beginners, in this blog we will be making these 2 methods : 

1. Array.push()

2. Array.concat()

and to make these methods we are allowed to use method that we have already build ,so let’s start.
Same as previous post,

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/66n35bb6eftgsw33vy3s.png)
First i will be introducing the array method with their example input and output, then we will examine those methods, identifying which programming tools and tricks to used and in which order to arrange them. Along that process we will build pseudocode algorithm for required function and later on, i will show you flowchart version of that algorithm, the important tip that i can give to you all, to get most out of this blog, is to first try to build it by yourself then come to this blog.

1. Array.push():

First is Array.push() method, The push method of array instances adds the specified elements to the end of an array and returns the new length of the array.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w5nmxbvya3wxgbkygbnf.png)
So, from looking at example input and output and definition of the method , we have to somehow calculate length of array and then return it. Well, remember we could use methods that we have already build, so we could use length method, actually property to find length of array.

Next, we have to add given element to the end of an array, but we can’t use push method so, how? Well, let’s go to basics, remember:

" JavaScript programming language supports dynamic arrays, which means that the array data structure can automatically adjust its size to accommodate new elements as they are added. This capability allows for flexible and efficient management of collections of data without needing to manually allocate and manage memory or resize the array."

Supporting dynamic arrays means that the array data structure can automatically adjust its size to accommodate new elements as they are added. This capability allows for flexible and efficient management of collections of data without needing to manually allocate and manage memory or resize the array.

### Key Features of Dynamic Arrays:

1. **Automatic Resizing**:
    - Dynamic arrays grow or shrink automatically as elements are added or removed. This is in contrast to static arrays, which have a fixed size that cannot be changed after they are created.
2. **Efficient Memory Management**:
    - Dynamic arrays manage memory allocation and reallocation internally. When the array reaches its capacity, it typically allocates a larger block of memory, copies the existing elements to the new block, and then continues adding new elements.
3. **Ease of Use**:
    - Users can add, remove, or access elements without worrying about the underlying memory management. This makes dynamic arrays much easier to use compared to static arrays, especially when the number of elements can vary.

### Examples in Various Languages:

### JavaScript

JavaScript arrays are inherently dynamic:

```
let arr = [1, 2, 3];
arr.push(4);  // Adds an element to the end of the array
console.log(arr);  // Output: [1, 2, 3, 4]
```

Python
Python lists are dynamic:

```
arr = [1, 2, 3]
arr.append(4)  # Adds an element to the end of the list
print(arr)  # Output: [1, 2, 3, 4]
```

Java
Java's ArrayList is a dynamic array:

```
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);  // Adds an element to the end of the ArrayList
        System.out.println(arr);  // Output: [1, 2, 3, 4]
    }
}
```
C++
C++'s std::vector is a dynamic array:

```
#include <vector>
#include <iostream>

int main() {
    std::vector<int> arr = {1, 2, 3};
    arr.push_back(4);  // Adds an element to the end of the vector
    for (int i : arr) {
        std::cout << i << " ";
    }
    // Output: 1 2 3 4
    return 0;
}
```
Another thing to note is,
arrays are zero-indexed, which means the first element is at index 0, the second element is at index 1, and so on. The length property (or equivalent) of an array provides the total number of elements in the array.

When you add an element to the end of an array, you place it at the index equal to the current length of the array because:

1.The indices of the existing elements range from 0 to length - 1.

2.The next available position is at the index length.

so, we just have to directly add or assign the element at the length index slash next available index.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dwbfqg8dgcdl88mcfgmx.png)
Now, its time to make rough draft of our algorithm, first initialize function cause we are making a function, let’s name it push taking two parameters array and element to add. Then assign element to array at next available index that would be length of an array. Finally, return array’s length.

Pseudocode:

- Initialize function named push
- assign element to array at next available index (length)
- return array’s length

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/va3d092p94p6zcl45s5d.png)

Here a flowchart representation of our algorithm: nothing complex

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jbl6v9sk16yz1g7wrcoe.png)
Now let’s code it up with javaScript:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qyvp897rhqt8mctpd7xx.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qytqky0ao3rmf5rcp4bm.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7td5t0m3yjncur7hefn.png)
In this implementation:

1. The new element `ele` is added at the index `arr.length`, which is the next available position in the array.
2. The length of the array is incremented automatically.
3. The function returns the new length of the array.

This custom `push` function works similarly to the native `Array.prototype.push` method. It modifies the original array and returns the new length of the array.

2. Array.concat():

Next is array’s concat method. The **concat** method of [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) instances is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pgajtbs6k4t6i2il7lgh.png)
So, how can we merge two arrays? If you think about it , merging an arrays is same as, taking individual elements and placing it in correct order into bigger array.

So, next logical step would be, if somehow expands the arrays into individual elements. And place them into larger array, then return that. that could work. 

Now, the question is how to expands the arrays into individual elements? Well, let’s go home again, i mean the basics. In array, we have study about spread operator, which does exactly what we need, which is to expands the array into individual elements.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ixg29xjeptqpufg4crc1.png)
and to concatenate, place the spread arrays inside square brackets ,we create a new array that includes all elements from both arrays.

Now, time for annoying part or for some or most, the fun part, edge case. What if passed down arguments aren’t of type array. For that, just throw an error.

so, updating our algorithm, check if both arrays are of type array. If not, then throw an appropriate error like “Both arguments should be arrays”.

Pseudocode :

- initialize function named concat.
- check if both arrays are of type array
- If not, then throw an appropriate error
- return a array inside which, two spread array in placed

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r1t05io7od1t1wsli0kn.png)
Here a flowchart representation of our algorithm: nothing complex

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v014cmr3k93d3gjzwqbq.png)
Now let’s code it up with javaScript:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hjpik9sv32u4tfo4y5q0.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/86zd91kwq5nwnwbtvkef.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5l7pfpcn1e2e70uy7rrn.png)

The spread operator (...) in JavaScript allows an iterable such as an array to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. This makes it a powerful tool for array manipulation, including concatenation.

How the Spread Operator Works
When you use the spread operator with arrays, it effectively breaks down the array into individual elements. This can then be used to create a new array containing elements from multiple arrays.

Example of Spread Operator for Concatenation
Here's an example to illustrate how the spread operator works for array concatenation:

```
const arr = [1, 2, 3];
const arr3 = [4, 5, 6];

// Using the spread operator to concatenate arrays
const concatenatedArray = [...arr, ...arr3];

console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5, 6]
```
### Step-by-Step Explanation

1. **Spread Syntax**: The spread operator `...arr` expands the array `arr` into individual elements. Similarly, `...arr3` expands `arr3`.
2. **Concatenation**: By placing the spread arrays inside square brackets `[ ...arr, ...arr3 ]`, we create a new array that includes all elements from both `arr` and `arr3`.

### Detailed Breakdown

- **Initial Arrays**:

- `const arr = [1, 2, 3];
const arr3 = [4, 5, 6];`
- **Using Spread Operator**:
    
    ```jsx
    const concatenatedArray = [...arr, ...arr3];
    
    ```
    
    This is equivalent to:
    
    ```jsx
    const concatenatedArray = [1, 2, 3, 4, 5, 6];
    
    ```
    
- **Output**:
    
    ```jsx
    console.log(concatenatedArray); // Output: [1, 2, 3, 4, 5, 6]
    
    ```
    

### Implementation in a Function
Here's the complete code including a function to concatenate arrays with input validation:

```jsx
function concat(arr, secondArray) {
  // Check if both inputs are arrays
  if (!Array.isArray(arr) || !Array.isArray(secondArray)) {
    throw new TypeError('Both arguments should be arrays');
  }

  // Concatenate arrays using the spread operator
  return [...arr, ...secondArray];
}

const arr = [1, 2, 3];
const arr3 = [4, 5, 6];

console.log(concat(arr, arr3)); // Output: [1, 2, 3, 4, 5, 6]

```

By leveraging the spread operator, array concatenation becomes more straightforward and intuitive.

```jsx
Thank you for reading, that's all for today.
```