w3resource

JavaScript slice() Method: Array Object

Description

The slice() method is used to extract a section of an array. The method returns a new array and it does not change the original array, selected elements of the original array are copied into a new array.

Version

Implemented in JavaScript 1.2

Syntax

slice(begin, end)

Parameters

begin: Specifies where to begin the extraction.

end: Specifies where to end the extraction.

The starting position is required and end position is optional, if end is omitted, slice extracts to the end of the sequence. As a negative index, end indicates an offset from the end of the sequence

Example -1

In the following web document, slice() method extract second and third elements from fruitslist and creates a new array.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8" />
<title>JavaScript slice() method example</title>
<style type="text/css">
h1 {color:red}
</style>
</head>
<body>
<h1>JavaScript : slice() method</h1>
<script src="array-slice-example1.js"></script>
</body>
</html>

JS Code

var fruitslist = new Array("Orange","Apple","Banana","Chery" );
var newParagraph = document.createElement("p"); 
var newText = document.createTextNode("List of Fruits : " + fruitslist); 
newParagraph.appendChild(newText); 
document.body.appendChild(newParagraph); 

var newfruitslist =fruitslist.slice(1,3);
var newParagraph = document.createElement("p"); 
var newText = document.createTextNode("Extract Fruits List : " + newfruitslist); 
newParagraph.appendChild(newText); 
document.body.appendChild(newParagraph); 

View the example in the browser

Practice the example online

JavaScript slice() method example

Example -2

In the following web document, slice() method extract last two elements from fruitslist and creates a new array.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf8" />
<title>JavaScript slice() method from last two - example
</title>
<style type="text/css">
h1 {color:red}
</style>
</head>
<body>
<h1>JavaScript : slice() method</h1>
<script src="array-slice-example2.js"></script>
</body>
</html>

JS Code

var fruitslist = new Array("Orange","Apple","Banana","Chery");
var newParagraph = document.createElement("p"); 
var newText = document.createTextNode("List of  Fruits : "+fruitslist);
newParagraph.appendChild(newText); 
document.body.appendChild(newParagraph); 
var newfruitslist = fruitslist.slice(0,-2);
var newParagraph1 = document.createElement("p"); 
var newText1 = document.createTextNode("Extract Fruits List : " + newfruitslist); newParagraph1.appendChild(newText1); 
document.body.appendChild(newParagraph1);

View the example in the browser

Practice the example online

JS Bin

See also:

JavaScript Core objects, methods, properties.

Previous: JavaScript shift() Method: Array Object
Next: JavaScript splice() Method : Array Object

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.