The slice() method in JavaScript returns a shallow copy of a portion of an array into a new array, without modifying the original array. It is non-destructive and ideal for copying, extracting subsets, or cloning arrays.
Key Features:
Syntax:
array.slice(start, end)start(optional): Index to begin extraction (inclusive). Defaults to0.end(optional): Index to end extraction (exclusive). Defaults to array length.
Negative indices count from the end:
-1is the last element,-2is the second-to-last, etc.Returns: A new array with the selected elements.
Examples:
const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
console.log(fruits.slice(1, 3)); // ['banana', 'cherry']
console.log(fruits.slice(2)); // ['cherry', 'date', 'elderberry']
console.log(fruits.slice(-2)); // ['date', 'elderberry']
console.log(fruits.slice()); // ['apple', 'banana', 'cherry', 'date', 'elderberry'] (full copy)Common Use Cases:
Cloning arrays:
const copy = original.slice();Pagination: Extracting a specific range of items.
Immutable updates: Safe for frameworks like React.
Working with array-like objects: Convert via
Array.prototype.slice.call(obj).
Note: Unlike
splice(),slice()does not mutate the original array. It is read-only and preserves the original data.
The second argument to Array.slice() is the upper bound of the slice.
Think of it as array.slice(lowestIndex, highestIndex).
When you slice from index 3 to index 100, there is one item (in your case) that has index >= 3 and < 100, so you get an array with that one item. When you try to take a slice from index 3 to index 0, there can't be any items that meet the conditions index >= 3 and < 0, so you get an empty array.
--EDIT--
Also, array.slice() should never return undefined. That's one of the advantages of using it. If there are no matching values in the array, you just get back an empty array. Even if you say var a = new Array() and don't add any values to it, calling a.slice(0,1) will just give you an empty array back. Slicing from outside of the array bounds will just return an empty array also. a.slice(250) will return [] whereas a[250] will be undefined.
javascript - using .slice method on an array - Stack Overflow
JavaScript Array splice vs slice - Stack Overflow
What's the difference between doing [].slice.call(array) and array.slice()? I've seen such []s used many times with the array inside the call. Why? Thanks!
javascript - array.slice(-1)[0] -- Can someone explain? - Stack Overflow
Videos
splice() changes the original array whereas slice() doesn't but both of them returns array object.
See the examples below:
var array=[1,2,3,4,5];
console.log(array.splice(2));
This will return [3,4,5]. The original array is affected resulting in array being [1,2].
var array=[1,2,3,4,5]
console.log(array.slice(2));
This will return [3,4,5]. The original array is NOT affected with resulting in array being [1,2,3,4,5].
Below is simple fiddle which confirms this:
//splice
var array=[1,2,3,4,5];
console.log(array.splice(2));
//slice
var array2=[1,2,3,4,5]
console.log(array2.slice(2));
console.log("----after-----");
console.log(array);
console.log(array2);
Splice and Slice both are Javascript Array functions.
Splice vs Slice
The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.
The splice() method changes the original array and slice() method doesn’t change the original array.
The splice() method can take n number of arguments and slice() method takes 2 arguments.
Splice with Example
Argument 1: Index, Required. An integer that specifies at what position to add /remove items, Use negative values to specify the position from the end of the array.
Argument 2: Optional. The number of items to be removed. If set to 0(zero), no items will be removed. And if not passed, all item(s) from provided index will be removed.
Argument 3…n: Optional. The new item(s) to be added to the array.
var array=[1,2,3,4,5];
console.log(array.splice(2));
// shows [3, 4, 5], returned removed item(s) as a new array object.
console.log(array);
// shows [1, 2], original array altered.
var array2=[6,7,8,9,0];
console.log(array2.splice(2,1));
// shows [8]
console.log(array2.splice(2,0));
//shows [] , as no item(s) removed.
console.log(array2);
// shows [6,7,9,0]
Slice with Example
Argument 1: Required. An integer that specifies where to start the selection (The first element has an index of 0). Use negative numbers to select from the end of an array.
Argument 2: Optional. An integer that specifies where to end the selection but does not include. If omitted, all elements from the start position and to the end of the array will be selected. Use negative numbers to select from the end of an array.
var array=[1,2,3,4,5]
console.log(array.slice(2));
// shows [3, 4, 5], returned selected element(s).
console.log(array.slice(-2));
// shows [4, 5], returned selected element(s).
console.log(array);
// shows [1, 2, 3, 4, 5], original array remains intact.
var array2=[6,7,8,9,0];
console.log(array2.slice(2,4));
// shows [8, 9]
console.log(array2.slice(-2,4));
// shows [9]
console.log(array2.slice(-3,-1));
// shows [8, 9]
console.log(array2);
// shows [6, 7, 8, 9, 0]
EDIT: Thanks for the answers, magnificent people! So Array.from is a better way than [].slice.call, and they're used to provide the array prototype to array-like objects! If done directly, apparently errors are thrown.
Thanks!
Break the expression down into its parts. By understanding each small piece, you will understand the whole.
This is your original statement: alert(array.slice(-1)[0]);
alert(...) is a function call. Before it can execute (and print something to the screen), its arguments must be evaluated first. It has one argument: array.slice(-1)[0], which we'll examine next.
array.slice(-1) is another function call. [0] is an array index. Which is evaluated first? To answer this, we turn to Operator Precedence. Both function calls and member access are level 19, with left-to-right associativity, which means we evaluate the function call first, then the array index next.
For this, let's turn to the documentation on array.slice, which says:
arr.slice(begin)
A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.
Return value
A new array containing the extracted elements.
So, array.slice(-1) gives you an array containing the last element from the original array.
Moving left-to-right, we now have an array of a single item followed by an array index [0]. That gives you the first (and only) item from the sliced array, which is then passed to the alert(...).
Check out Array.prototype.slice().
When you call array.slice(), that's returning a slice of your array (as another array).
var array = ['zero', 'one', 'two', 'three'];
// Grab the elements from `array`
// beginning at 1 and up to (not including) 3.
var sliced = array.slice(1, 3);
console.log(array); // ['zero', 'one', 'two', 'three']
console.log(sliced); // ['one', 'two']
console.log(sliced[0]) // 'one'
In your code, you are executing array.slice(-1). The documentation says that "[a] negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence." Thus, your array.slice(-1) is returning a new array populated with the last element of your original, array.
var array = ['zero', 'one', 'two', 'three'];
var sliced = array.slice(-1);
console.log(array); // ['zero', 'one', 'two', 'three']
console.log(sliced); // ['three']
console.log(sliced[0]); // 'three'
// All together, it looks like this.
// I'm using `alert()` instead of `console.log()`
// to mirror your code.
alert(array.slice(-1)[0]); // 'three'
In javascript, strings are enclosed in quotes. e.g.
'john', "mike" ect. so in order to create an array/list you need to put these values with quotes inside array and then access using index e.g.
var array = ['john', 'mike', 'tom']
console.log(array[0]); // john
Why do you need the strings to not have quotes? Is there an specific reason?
In js you need to put quotes on strings. If you try for example declaring an array in the way you did above the following will happen:
let x = [janaina,joao,julia]
VM203:1 Uncaught ReferenceError: janaina is not defined at :1:10
So, correct way to delcare your array:
let x = ['janaina','joao','julia']
Now slice will work:
x.slice(0,1);
The result will be:
['janaina']