.slice method. How does it work, please help to explain



let groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];

groceryList.shift();

groceryList.unshift('popcorn');
console.log(groceryList);

console.log(groceryList.slice(1, 4));
console.log(groceryList);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

There are three possible usages of this string method.

slice()

will make a copy of an array. This creates a new reference object, not just a new reference to the old object. The copy is independent.

const a = new Array(16).fill('X');
let b = a.slice();
console.log(b);
/* =>
['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
*/
b[15] = 'F'
console.log(b);
/* =>
['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'F']
*/
console.log(a);
/* =>
['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
*/

The thing to keep in mind about the slice() method is that it is a copy function, not a manipulator or mutation function.

Next let’s look at position to end slicing…

let c = b.slice(8);
console.log(c);
// => ['X', 'X', 'X', 'X', 'X', 'X', 'X', 'F']

The above is a slice consisting of the latter eight elements of the full slice. (The number 8 above is the index, not the count.) It does not affect the object it is sliced from as we have already determined that it is a copy, only, and it is independent of the original so exclusively mutable.

Next we look at point to point slicing.

b[4] = '4';
b[11] = 'B';
let d = b.slice(4, 12);
console.log(d);
// => ['4', 'X', 'X', 'X', 'X', 'X', 'X', 'B']

Always keep at the top of your mind the concept of zero-indexing and how it plays into things. It is so simple but so blustering at the same time. Really does throw us off, sometimes.

'4'

is at index 4 because '0' would be at index 0. But why is B at index 12? Answer: It’s not, really, but because it is the twelfth item in the sequence. The end is the first non-existent element index. Little things like this will catch up even a seasoned writer. That’s why we test our assumptions in a small space to make sure we’re not blowing smoke up any skirts.

The last model to examine is from the beginning to a point, which is more or less covered above so we can extrapolate from it…

let e = b.slice(0, 8); 
console.log(e);
// => [ 'X', 'X', 'X', 'X', '4', 'X', 'X', 'X' ]

From all this we can conclude that, no arguments means a full slice, end to end; one argument means start at that index and take everything to the end; two arguments means start and end, both of which are indices as described above…

4 Likes

Thank you very, this is very helpful

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.