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 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,
begin
is a position where to start the extraction.end
is a position where to end the extraction.Note that, about js array slice()
method:
begin
is undefined, slice
begins from the index 0
.end
is omitted, slice
extracts through the end of the sequence (arr.length
).Let’s take a look example of js array.slice() method:
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.
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.
In this tutorial, you have learned JavaScript array slice()
method and how to use it.
☞ 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