How to Use the slice method in JavaScript

  • 5 min read
  • November 2, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

The slice() method is a part of both the Array and String prototypes, and can be used with either type of object.

The method returns items (from arrays) or characters (from strings) according to the provided indices. As its name suggests, it takes a slice from the entity it is applied to. This happens without modifying the original array or string, meaning you essentially get to slice the cake and leave it whole at the same time!

Array.slice() example

Let’s explore how slice() works with Array objects using the following example:

const nums = [1, 23, 45, 56, 64, 102];
const firstNums = nums.slice(0, 3);
console.log(firstNums);
// Expected output: [1, 23, 45]

In the code above, the slice() method is used to create a copy of the first three numbers of the nums array (as indicated by the provided parameters: 0, 3). const firstNums points to this copy.

String.slice() example

Applying the same syntax, it is possible to extract a portion of a String value.

const code = 'I love to code';
const love = code.slice(2, 6);
console.log(love);
// Expected output: love

In the example above, the slice() method is used to extract the characters between indices 2 and 6. In the provided string const code, these characters spell ‘love’.

Syntax

As we see above, the syntax for the slice() method is very straightforward. Simply apply the slice method to a String or an Array, passing in the index where you wish the slice to begin (which is included in the returned copy) and the index where the slice should end (which is not included in the returned copy).

This method returns a new Array or String. The syntax is as follows

String or Array.slice(startIndex, endIndex)

  • startIndex: where to start the extraction from the parent object. Note that indices in JavaScript start at 0.

If startIndex is undefined, the extraction begins at index 0.

If the index provided is greater than the length of the parent String or Array, an empty string or empty array is returned as appropriate. The length of an Array is the number of items contained in the array, while the length of a String is the number of characters contained in the string.

  • endIndex (optional): the point at which the extraction operation will stop.

Note: The value at this index is not included in the returned copy.

This parameter is optional. If omitted, the extraction will continue until the end of the String or Array. The same result occurs if you provide an index that is greater than the length of the String or Array.

Applying the slice() method with no parameters passed copies the entire array or string.

Negative index

It is possible to provide negative numbers as either argument for the slice() method. When negative numbers are provided, the index count begins from the end of the Array or String (e.g. -1 refers to the second-to-last element):

const nums = [1, 23, 45, 56, 64, 102];
const midNums = nums.slice(2, -2);
console.log(midNums);
// Expected output: [45, 56]

In the example above, the extraction from const nums begins at index = 2 (the third item in the array), and continues until reaching the last 2 items in the array (due to the endIndex being -2). Therefore, only the two middle items are included in the resulting new array (const midNums).

Important note

JavaScript Objects (including JavaScript Arrays) are stored by reference in variables. This means that variables in JavaScript act as pointers to the object’s value. When applying the Array.prototype.slice() method to make a copy of an array which includes an object, the reference to this data is being copied. Any change made to the object will change both the object in the original array as well as the object in the copy.

While this may seem complicated, the below example shows how this works:

const user = { name: 'Mike', psw: '45qy34' };
const luckyNnums = [14, 23, 32, 44];
const userNums = [user, luckyNnums];
console.log(userNums);
// Expected output: [
// {name: "Mike", psw: "dhue32"},
// [14, 23, 32] ]
const userNumsCopy = userNums.slice();
user.psw = 'dhue32';
luckyNnums.pop();
console.log(userNumsCopy);
// Expected output: [
// {name: "Mike", psw: "dhue32"},
// [14, 23, 32] ]

Let’s break down the above example:

const user points to an object.

const luckyNums points to an array.

const userNums points to an array that includes references to both const user and const luckyNums.

Note that the first time we print the array userNums to the console, the values have already changed – this is odd, as it seems to have happened prior to the changes in value being made to the array in subsequent lines of code. This is because we are working with a reference to this same data at later points in the code, thus when the console.log() statement is evaluated, the underlying data has already changed.

const userNumsCopy points to an array which is a copy of const userNums.

The next line – user.psw = ‘dhue32’ assigns new value to const user’s psw key.

Then, one lucky number is removed from luckyNnums by applying the pop() method.

The second print to the console is exactly the same as the first, but it is now the print of the copy – const userNumsCopy.

Since objects are stored as references, when a change is made, the value in all references changes. The variables simply point to the object, which is now different, and the differences are reflected in all instances of these objects.

 

Related Articles

JavaScript – Arrays Explained

JavaScript – How to Use the indexOf method

JavaScript – How to Search Arrays

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement

How to use the for…of Statement in JavaScript

How to use the for…of Statement in JavaScript

The for…of statement was introduced in ECMAScript2015 (ES6) and adds a powerful new type of loop to JavaScript. JavaScript offers many different types of loops, each