3. Building JavaScript Array Methods from Scratch in 2024 - Easy tutorial for beginners.
Tags: javascript, beginners, tutorial, learning
Published: 2024-06-19 15:35:57

Video version's link: https://www.youtube.com/watch?v=cJpmCjRJB3A

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vb3mp6pfyaj0do69617f.png)
Continuing our series of building javaScript method from Scratch for beginners from javaScript programming basics. In this post we will be making these 2 method as a function:

1. Array.pop()
2. Array.at()

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

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

1. Array.pop():

First is Array.pop() method. The **pop** method of [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) instances removes the **last** element from an array and returns that element. This method changes the length of the array.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6zbl7409bgile6u2bsd2.png)
By examining the example input, output, and the method's definition, to build this method as a function we have to somehow extract array’s last element and return it. And removing the last element means after the pop method is executed array will be missing it’s last position element.

So these are the two things we are focusing on, first extracting last element, extracting element from array requires element’s position index. Now let’s take simplest case possible, array with only one element. We extract last element of that kind of array by taking index as 0 . And for array containing 2 elements, we can extract last element by taking index as 1 and for 3 element containing array the index would be 2.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8frbqvf6rkunwzj715xk.png)
Now, Can you see the pattern here? To extract the last element of the array, we need an index which is length of an array minus 1.

Now the second constraint. For second constraint which is to remove the last element of an array and adjusting the length of an array. Well, listen me out for this one, what if i say adjusting length of an array which is decreasing the length of a JavaScript array by 1 can automatically remove the last element.

Let me explain: When you decrease the length of a JavaScript array by 1, it effectively removes the last element from the array. This is because the length property of an array in JavaScript is not just a property that you can read, but also a property you can write to. By setting a new length for the array, you can effectively truncate the array, removing elements that are beyond the new length.

When you change the length of the array, JavaScript automatically removes any elements that are beyond the new length. So, if the original array was [1, 2, 3] and you set arr.length = 2, the array becomes [1, 2]. The element 3 is no longer part of the array.

So now the all the missing pieces are here, let make a rough draft of our algorithm which is called pseudocode. First, initialize a function, let’s name it customPop. It’s excepts one argument: an array. Second, Extract last element of an array by assigning it to a variable “lastElement”, a reasonable name. Then decrease the length property of that array by 1. And finally, return variable “lastElement”.

- Initialize a function named customPop, parameter ; arr
- Initialize a variable lastElement
- Assign last element of an array to variable lastElement
- Minus the length property of that array by 1
- return variable lastElement

All done, but one case that we have not take care of is when, given array is empty, meaning array’s length is 0, in that case we have to return undefined.

modifying the algorithm, after initializing the function, check if array’s length is zero, if yes then return undefined.

- Initialize a function named customPop, parameter ; arr
- check if array’s length is zero
- if yes then return undefined
- Initialize a variable lastElement
- Assign last element of an array to variable lastElement
- Minus the length property of that array by 1
- return variable lastElement

Here a flowchart representation of our algorithm:

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

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

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5l4xy7p9rgxqcan40896.png)
```jsx
function customPop(arr) {
    if (arr.length === 0) {
        return undefined;  // If the array is empty, return undefined
    }

    const lastElement = arr[arr.length - 1];  // Get the last element
    arr.length = arr.length - 1;  // Decrease the length of the array by 1, effectively removing the last element
    return lastElement;  // Return the removed element
}

const array = [1, 2, 3];
console.log(customPop(array));  // Output: 3
console.log(array);  // Output: [1, 2]
console.log(customPop(array));  // Output: 2
console.log(array);  // Output: [1]
console.log(customPop(array));  // Output: 1
console.log(array);  // Output: []
console.log(customPop(array));  // Output: undefined
```
### Explanation

1. **Check if the Array is Empty**:
    - If the array has no elements (`arr.length === 0`), return `undefined`.
2. **Get the Last Element**:
    - Store the last element of the array in a variable (`lastElement`).
3. **Remove the Last Element**:
    - Decrease the length of the array by 1 (`arr.length = arr.length - 1`). This effectively removes the last element from the array.
4. **Return the Removed Element**:
    - Return the stored last element (`lastElement`).

This custom `pop` function works similarly to the built-in `pop` method, adjusting the array's length to remove the last element and returning that element.
**2. Array.at()**

Next one on the line is [array.at](http://array.at/) method. The **at** method of [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) instances takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ra15s9q2gg5c4gsws8q.png)
Well, if given index is an positive integer and is within the bound of an array then its easy, just access a element and return. Problem arises when given index is not an integer, and if it is, it is not positive integer. Remember we can only access element in array with positive integer value. And another constraint is that index have to be within the bound of an array.

So let’s tackle these constraints one by one, first check if given index is an integer, otherwise return undefined. We can check if given index is an integer by using Number.isInteger method, which is a static method determines whether the passed value is an integer.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ntpafiu343i6wy2fs3pi.png)
Secondly, for negative index passed down to a function, we have to convert it into it’s positive equivalent index. So how would we do it? again, let’s start by taking simplest case possible, array with only one element. In this array, we can only access one element, the 0 index element which corresponding negative index is -1. And how we convert -1 to 0? simple by adding 1. And in array with 2 elements, 0 index corresponding negative index is -2.

Can you see the pattern here? As length of an array increase, 0 index corresponding negative index decreases. So, To get positive index of an element from negative index, just add it with length of an array.

And importantly, we have to convert negative index into positive before this step, as it is easier check this condition with positive index. And if index is not within the bound we will return undefined.

Now let’s write our algorithm of custom at function in simple English sentences: First we initialize a function with two parameters; array and index. Let’s name it customAt. And this time let’s start with checking if given array is of type array, as i have shown you how to do it, quite a few times in this series. And if given array is not of type array then throw an appropriate error.

Secondly, check if given index is an integer, if not then return undefined. Next, check if given index is negative, if yes then add array’s length to it. Next, check if index is within the bound of array, if not then return undefined. And finally, return required element corresponding array’s index.

- Initialize function named customAt, parameters ; array and index
- check if array is of type array
- If not, then throw an appropriate error
- check if given index is an integer
- if not then return undefined
- check if given index is negative
- if yes then add array’s length to it
- check if index is within the bound of array
- if not then return undefined
- return required element corresponding array’s index.

Here a flowchart representation of our algorithm:

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

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

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7mbh6new1hi4f7uyt271.png)
```jsx
function customAt(array, index) {
  // Check if the input is an array
  if (!Array.isArray(array)) {
    throw new TypeError('The first argument must be an array');
  }

  // Check if the index is an integer
  if (!Number.isInteger(index)) {
    throw new TypeError('The index must be an integer');
  }

  // Handle negative indices
  if (index < 0) {
    index += array.length;
  }

  // Check if the index is within bounds
  if (index < 0 || index >= array.length) {
    return undefined;
  }

  return array[index];
}

// Example usage:
const arr = [1, 2, 3, 4, 5];

console.log(customAt(arr, 2)); // Output: 3
console.log(customAt(arr, -1)); // Output: 5
console.log(customAt(arr, -3)); // Output: 3
console.log(customAt(arr, 5)); // Output: undefined
console.log(customAt(arr, -6)); // Output: undefined
console.log(customAt(arr, 2.5)); // Output: Error: The index must be an integer

```

### Explanation:

1. **Input Validation**:
    - The function first checks if the input is an array using `Array.isArray()`.
    - If the input is not an array, a `TypeError` is thrown.
2. **Integer Check**:
    - The function checks if the index is an integer using `Number.isInteger()`.
    - If the index is not an integer, a `TypeError` is thrown.
3. **Negative Index Handling**:
    - If the index is negative, it is adjusted by adding the array’s length to it (`index += array.length`).
4. **Bounds Checking**:
    - The function checks if the adjusted index is within the bounds of the array.
    - If the index is out of bounds (either less than 0 or greater than or equal to the array’s length), the function returns `undefined`.
5. **Element Retrieval**:
    - If the index is within bounds, the function returns the element at the specified index.

This implementation ensures that the index must be an integer and provides the same functionality as the `Array.prototype.at()` method, allowing for both positive and negative indexing and robust error handling.

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