What is the _.slice() method in Lodash?

Overview

The _.slice() method in Lodash is used to create a slice of an array from the start, and up to but excluding the end.

Syntax

_.slice(array, start, end)
_.slice() Syntax

Parameters

This method accepts the following parameters:

  • array: This is the array to be sliced.
  • start: This is the start from where the array will be sliced. If not specified, it will take 0 as default.
  • end: This is the end until where the array will be sliced. If not specified, it will take the length of the array as the default.

    Return value

    This method returns a slice of an array.

    Example

    Let’s look at an example of the _.slice() method in the code snippet below.

    Console
    Implementation of the _.slice() method

    Explanation

    In the HTML tab, we see the following.

    • Line 5: We import the lodash script.

    In the JavaScript tab, we see the following.

    • Line 2: We create an array and initialize it with a few values.
    • Line 5: We create a variable start and initialize it with 2.
    • Line 8: We create a variable end and initialize it with 4.
    • Line 11: We use the _.slice() method to slice the array.
    • Line 14: We print the output to the console.

    Output

    In the output, we see a slice of the array.

    Free Resources