What is JavaScript Array slice ?
Array.prototype.slice is a JS Array method that is used to extract a contiguous subarray or "slice" from an existing array.
JavaScript slice can take two arguments: the start and the end indicator of the slice -- both of which are optional. It can also be invoked without any argument. So, it has the following call signatures:
// slice(); slice(start); slice(start, end);
If I want to slice the array to take a portion of it, there actually has a built-in function slice for Javascript. Right out of the box, it’ll clone the original array.
[1,2,3].slice() // [1,2,3]
The result points to a new memory address, not the original array. This can be really useful if you want to chain the result with other functions. The real usage is when you provide some input to the slice.
Start Index
The slice can take up to two input parameters. The first one is called the start index, and this would tell where it should start the slice.
[1,2,3].slice(0) // returns [1,2,3]; Original array unmodified [1,2,3].slice(1) // returns [2,3]; Original array unmodified [1,2,3].slice(2) // returns [3]; Original array unmodified [1,2,3].slice(3) // returns []; Original array unmodified
By default, it’ll slice till the end of the array. The interesting thing about the start index is that not only you can use a zero or a positive number, but also you can use a negative number.
[1,2,3].slice(-1) // [3] [1,2,3].slice(-2) // [2,3] [1,2,3].slice(-3) // [1,2,3]
When it’s a negative number, it refers to an index counting from the end n . For instance, -1 refers to the last element of the array, -2 refers to the second last element, and etc. Notice there’s no -0 , because there’s no element beyond the last element. This can be quite apparent or confusing depending on the situation.
End index
The slice can take a second parameter called the end index.
[1,2,3].slice(0,3) // [1,2,3] [1,2,3].slice(0,2) // [1,2] [1,2,3].slice(0,1) // [1]
The end index, also referred as a range index, points to the element index + 1. What does it mean? To explain this, it would be relatively easier if we can relate to the for statement:
for (let i = 0; i <p>The variable i starts at 0 , the start index; and ends at n, the end index. The end index isn’t the last element of the array, because that would be n - 1 . But when it comes to the end index, n stands for the “end” with the the last element included. If it’s your first time using the end index, just remember how for statement is written, or simply remember taking the last element index and then plus one to it. Another way to think of it is that the end index is open ended, [start, end).</p> <p>As in the start index, the end index can be negative as well.<br> </p> <pre class="brush:php;toolbar:false">1,2,3].slice(0,-1) // [1,2] [1,2,3].slice(0,-2) // [1]
Pay a bit more attention here. -1 refers to the last element, therefore if used as the second parameter, it means the last element will be excluded, as we have explained, open ended.
Kool but what if I want to include the last element?
[1,2,3].slice(0) // [1,2,3]
Yes, simply use the single parameter input.
How to Use JavaScript slice: Real Example
A typical example of slicing an array involves producing a contiguous section from a source array. For example, the first three items, last three items and some items spanning from a certain index up until another index.
As shown in the examples below:
const elements = [ "Please", "Send", "Cats", "Monkeys", "And", "Zebras", "In", "Large", "Cages", "Make", "Sure", "Padlocked", ]; const firstThree = elements.slice(0, 3); // ["Please", "Send", "Cats"] const lastThree = elements.slice(-3, elements.length); // ["Make", "Sure", "Padlocked"] const fromThirdToFifth = elements.slice(2, 5); // ["Cats", "Monkeys", "And"]
If we don't pass any argument to JavaScript slice, we get a shallow copy of the source array with all items:
const allCopied = elements.slice(); // (12) ["Please", "Send", "Cats", "Monkeys", "And", "Zebras", "In", "Large", "Cages", "Make", "Sure", "Padlocked"]
It's effectively [...elements].
JavaScript Array slice Method with No Second Argument
If we don't pass the second argument, the extracted JavaScript Array slice extends to the last element:
const fromThird = elements.slice(2); // (10) ["Cats", "Monkeys", "And", "Zebras", "In", "Large", "Cages", "Make", "Sure", "Padlocked"] const lastThree = elements.slice(-3, elements.length); // (3) ["Make", "Sure", "Padlocked"] const lastThreeWithNoSecArg = elements.slice(-3); // (3) ["Make", "Sure", "Padlocked"]
JavaScript Array.prototype.slice with Negative Offsets
Notice also above that, we can pass in negative numbers as arguments. Negative values of the arguments denote offset positions counted backwards from the last item. We can do this for both arguments:
const latestTwoBeforeLast = elements.slice(-3, -1); // (2) ["Make", "Sure"]
If we pass in a greater value for start than end, we get an empty array:
const somewhereWeDontKnow = elements.slice(5, 2); // []
This indicates we have to always start slicing from a lesser positive index.
Array.prototype.slice: Starting Position Greater Than Length of Array
Likewise, if we pass in a greater value for start than array's length, we get an empty array:
const somewhereInOuterSpace = elements.slice(15, 2); // []
Using JS slice with Sparse Arrays
If our target slice has sparse items, they are also copied over:
const elements = [ "Please", "Send", , "Cats", , "Monkeys", "And", "Zebras", "In", "Large", "Cages", "Make", "Sure", "Padlocked", ]; const sparseItems = elements.slice(0, 6); // (6) [ 'Please', 'Send', , 'Cats', , 'Monkeys' ]
Array.prototype.slice: Creating Arrays from a List of Arguments
In this section we go a bit crazy about slicing. We develop two interesting ways with Array.prototype.slice to construct an array from a list of arguments passed to a function.
The first one:
const createArray = (...args) => Array.prototype.slice.call(args); const array = createArray(1, 2, 3, 4); // (4) [1, 2, 3, 4]
That was easy.
The next level way of doing this is in the messiest possible way:
const boundSlice = Function.prototype.call.bind(Array.prototype.slice); const createArray = (...args) => boundSlice(args); const array = createArray(1, 2, 3, 4); // (4) [1, 2, 3, 4]
Slicing a JavaScript String
const mnemonic = "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked"; const firstThreeChars = mnemonic.slice(0, 3); // "Ple" const lastThreeChars = mnemonic.slice(-3, mnemonic.length); // "ked" const fromThirdToFifthChars = mnemonic.slice(2, 5); // "eas"
Again, both arguments represent zero-based index numbers or offset values. Here too, the first argument -- 0 in the firstThree assignment -- stands for the starting index or offset in the source array. And the second argument (3) denotes the index or offset before which extraction should stop.
JavaScript String Slice Nuances
Using JavaScript String slice With No Arguments
Similar to Array slice, if we don't pass any argument to String slice(), the whole string is copied over:
const mnemonic = "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked"; const memorizedMnemonic = mnemonic.slice(); // "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked"
JavaScript String slice with Negative Offsets
Similar to Array.prototype.slice, negative values for start and end represent offset positions from the end of the array:
const mnemonic = "Please Send Cats Monkeys And Zebras In Large Cages Make Sure Padlocked"; const lastThreeChars = mnemonic.slice(-3); // "ked" const latestTwoCharsBeforeLast = mnemonic.slice(-3, -1); // "ke"
Summary
In this post, we expounded the slice() method in JavaScript. We saw that JavaScript implements slice() in two flavors: one for Arrays with Array.prototype.slice and one for Strings with String.prototype.slice. We found out through examples that both methods produce a copy of the source object and they are used to extract a target contiguous slice from it.
We covered a couple of examples of how function composition and context binding with Function.prototype.call and Function.prototype.bind allows us to define custom functions using Array.prototype.slice to help us generate arrays from a list of arguments.
We also saw that String.prototype.slice is an identical implementation of Array.prototype.slice that removes the overhead of converting a string to an array of characters.
The above is the detailed content of Javascript Slice method with Example. For more information, please follow other related articles on the PHP Chinese website!

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
