Javascript Slice method with Example
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 < n; i++) {}
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).
As in the start index, the end index can be negative as well.
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', <1 empty item>, 'Cats', <1 empty item>, '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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
