The slice() method of JavaScript is used to return the selected elements in an array.
The syntax is as follows −
array.slice(start, end)
Above, start parameter is an integer specifying where to begin the selection, whereas, end is where the selection ends.
Let us now implement the slice() method in JavaScript −
Example
<!DOCTYPE html> <html> <body> <h2>Demo Heading</h2> <p id="test"></p> <script> var arr = ["Accessories", "Electronics", "Books", "Pet Supplies"]; document.getElementById("test").innerHTML = "Initial array = "+arr+", <br>Sliced = "+arr.slice(2, 4); </script> </body></html>
Output
Example
<!DOCTYPE html> <html> <body> <h2>Car Variant</h2> <button onclick="display()">Result</button> <p id="test"></p> <script> var car = ["Hatchback", "Convertible", "SUV", "AUV", "MUV"]; document.getElementById("test").innerHTML = "Initial Array = "+car; function display() { document.getElementById("test").innerHTML = "Array after slicing some elements = "+car.slice(1,4); } </script> </body></html>
Output
Click “Result” button −