Press ESC to close

JavaScript slice

0 1509

In this lesson we will talk about the JavaScript slice method useful for selecting elements of an array.

This method returns a new array with the selected elements.

The syntax of slice() is as follows: array.slice(start, end).

The start and end parameters are optional. The beginning is a numerical value that indicates where the selection starts from, while the end is always a numerical value that indicates where the selection ends.

Be careful though. The initial array will not be modified, so to get the selection we can store it in a variable and then use it where needed.

JavaScript slice – first example

Take an array of 7 elements as input and select only the second and fourth.

First we take our array of 7 numbers as input.



var numbers = [5,4,3,2,6,9,62];

Then, using the slice method, we select the required elements or the second and fourth. We store the selection made in a variable, for example a result name.

Finally we display the result in the browser console.



var result = numbers.slice(2,4);
console.log(result);

As we can see by testing it, an array with the selected elements will appear in the console.

JavaScript slice – second example

We select all the elements of an array of strings starting from the second.

Suppose we have this array of strings:



var objectsSchools = ['pencil', 'eraser', 'sharpener', 'notebook', 'pencil'];

Then we use the slice method by specifying only the first parameter.



var result = objectsSchools.slice(2);
console.log(result);

In the console we will see all the elements starting from the second: Array (3) [“sharpener”, “notebook”, “pencil”].

So if we do not specify the second parameter, all the elements are selected up to the end of the array.

If, on the other hand, we do not even specify the first parameter, we will clearly have a copy of the starting array.

Conclusion

In this lesson we have approached the slice method of JavaScript through practical examples.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Other stories

JavaScript join

Next Story

JavaScript forEach

Previous Story