JavaScript Array slice() Method

You are Here:

JavaScript Array slice() Method

The slice() method returns the selected elements (from start index to end index) in an array, as a new array object.

Note: This method does not alter the original array.

Default start index and end index

In the following example, we will omit both start index and end index, so that the JavaScript will assign the default value to both.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Start from array index 3 to the length of an array.</p> <script> var myNumber = [1, 2, 3, 4, 5, 6, 7]; var newArray = myNumber.slice(); document.write("newArray = " +newArray); document.write("<br> myNumber = " +myNumber); </script> </body> </html>

Syntax

Array.slice(start, end)

Parameter Values

ValueTypeExplanation
startOptionalSpecifies the starting index of an array to be selected.
A negative index can be used to select the array elements in reverse order i.e., from right to left.
If omitted, the default value is '0'.
endOptionalSpecifies the ending index of an array to be selected.
A negative index can be used to select the array elements in reverse order i.e., from right to left.
If omitted, the default value is the 'length of an array'.

Specific start index and Default end index

In the following example, we will specify the value for the start index and the browser will assign the default value for the end index.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>From array index 3 to the length of an array</p> <script> var myNumber = [1, 2, 3, 4, 5, 6, 7]; var newArray = myNumber.slice(3); document.write("newArray = " +newArray); document.write("<br> myNumber = " +myNumber); </script> </body> </html>

Specific start index and end index

In the following example, we will specify the value for both the start index and end index.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Start from array index 1 and end right before array index 3.</p> <script> var myNumber = [1, 2, 3, 4, 5, 6, 7]; var newArray = myNumber.slice(1, 3); document.write("newArray = " +newArray); document.write("<br> myNumber = " +myNumber); </script> </body> </html>

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author