Array slice()

In this chapter you will learn:

  1. How to slice a Javascript array
  2. How to use negative value with slice method

Array slice()

slice() returns the sub-array. The slice() method may accept one or two arguments:

  • the starting
  • stopping positions.

slice(startingPoint) returns sub-array between startingPoint and the end of the array.

slice(startingPoint,endPosition) returns sub-array between the startingPosition and endPosition, not including the item in the end position.

slice() does not affect the original array in any way.

<!DOCTYPE html><!-- j a v a  2 s .  com-->
<html>
<head>
    <script type="text/javascript">
        var colors = ["A", "B", "C", "D", "E"]; 
        var colors2 = colors.slice(1); 
        var colors3 = colors.slice(1,4); 
        document.writeln(colors2); //B,C,D,E
        document.writeln(colors3); //B,C,D
       
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

The code above generates the following result.

slice negative value

If either the start or end position of slice() is a negative number, then the number is subtracted from the length of the array.

For the array in the following code, arrayWithFiveItem.slice(-2, -1) is the same as arrayWithFiveItem.slice(3, 4).

<!DOCTYPE html><!--   ja v a2 s .c o  m-->
<html>
<head>
    <script type="text/javascript">
        var colors = ["A", "B", "C", "D", "E"]; 
        var colors2 = colors.slice(-2,-1); 
        var colors3 = colors.slice(3,4); 
        document.writeln(colors2); //D
        document.writeln(colors3); //D
       
    </script>
</head>
<body>
</body>
</html>

Click to view the demo

If the end position is smaller than the start, then an empty array is returned.

Next chapter...

What you will learn in the next chapter:

  1. How to some() function to check each value in a Javascript array
Home » Javascript Tutorial » Array
Array Type
Array creation
Array type detecting
Array iterate
Array Length
Add to Array
Array join
Array concat()
Array every method
Array search from start with indexOf()
Array search from the end with lastIndexOf()
Array filter
Array mapping
Array forEach
Array pop and push
Array shift()
Array reduce()
Array reduceRight()
Array reverse()
Array slice()
Array some()
Array splice()
Array sort()
Array toString()
Array unshift()