How to slice an array with wrapping in JavaScript

Let's say, we are required to write an array method that overwrites the default Array.prototype.slice(). Usually the Array.prototype.slice() method takes in two arguments the start index and the end index, and returns a subarray of the original array from index start to end-1.

What we wish to do is make this slice() function so it returns a subarray from index start to end and not end-1. We iterate over the array using a for loop which is faster than many array methods. Then return the required subarray, lastly we overwrite the Array.prototype.slice() with the method we just wrote.

Understanding Default slice() Behavior

The default slice() method excludes the end index:

const arr = [5, 5, 34, 43, 43, 76, 78, 3, 23, 1, 65, 87, 9];

// Default slice() - excludes end index
console.log("Default slice(0, 4):", arr.slice(0, 4)); // indices 0,1,2,3
console.log("Default slice(5, 8):", arr.slice(5, 8)); // indices 5,6,7
Default slice(0, 4): [ 5, 5, 34, 43 ]
Default slice(5, 8): [ 76, 78, 3 ]

Custom slice() Implementation

Here's our custom implementation that includes the end index:

const arr = [5, 5, 34, 43, 43, 76, 78, 3, 23, 1, 65, 87, 9];

const slice = function(start = 0, end = this.length-1){
    const part = [];
    for(let i = start; i <= end; i++){
        part.push(this[i]);
    };
    return part;
};

Array.prototype.slice = slice;

console.log("Modified slice(0, 4):", arr.slice(0, 4));
console.log("Modified slice(5, 8):", arr.slice(5, 8));
console.log("Modified slice():", arr.slice());
Modified slice(0, 4): [ 5, 5, 34, 43, 43 ]
Modified slice(5, 8): [ 76, 78, 3, 23 ]
Modified slice(): [
  5, 5, 34, 43, 43, 76,
  78, 3, 23, 1, 65, 87,
  9
]

Key Differences

Method slice(0, 4) Includes End Index?
Default slice() [5, 5, 34, 43] (4 items) No
Custom slice() [5, 5, 34, 43, 43] (5 items) Yes

How It Works

The custom function uses i instead of i , making it include the element at the end index. The default parameters handle cases where start or end are not provided.

Conclusion

This custom slice() implementation includes the end index, unlike the default behavior. While overriding native methods isn't recommended in production, this demonstrates how array slicing logic can be modified.

Updated on: 2026-03-15T23:18:59+05:30

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements