JavaScript Array Slice() | Extract Elements From Array

JavaScript Array Slice() | Extract Elements From Array
In this tutorial, you will learn all about the JavaScript array slice() method and how to use it.

In this tutorial, you will learn all about the JavaScript array slice() method and how to use it.

By using js array slice() method, you perform different tasks like, you can copy the array, create a new array from given array, without changing the original array.

JavaScript Array slice() method

Javascript array slice() method extracts a part of an array from a given array and returns a new array.

The following syntax represents the slice() method:

slice(begin, end);

Here,

  • The begin is a position where to start the extraction.
  • The end  is a position where to end the extraction.

Note that, about js array slice() method:

  • If begin is undefined, slice begins from the index 0.
  • If end is omitted, slice extracts through the end of the sequence (arr.length).

Let’s take a look example of js array.slice() method:

Example 1: Clone an array

The following example shows how to clone an array using the js array slice() method:

var nums = [1,2,3,4,5];
var res = nums.slice();

In this example, the res array contains all the elements of the nums array.

Example 2: Copy a portion of an array

The following example shows how to copy the portion of an array without changing the original array using the slice() method.

See the following example:

var lang = ['php','java','c','c#','.net', 'python'];
var res = lang.slice(0,4);
console.log(res); // ["php", "java", "c", "c#"]

The res array contains the first 4 elements of the lang array. The original array lang remains entire.

Conclusion

In this tutorial, you have learned JavaScript array slice() method and how to use it.

Suggest:

Learn Vue.js from scratch 2018

Learn JavaScript - Become a Zero to Hero

JavaScript Programming Tutorial Full Course for Beginners

Vue js Tutorial Zero to Hero || Brief Overview about Vue.js || Learn VueJS 2023 || JS Framework

JavaScript for React Developers | Mosh

An Encounter with JavaScript Objects