Patrickkx Patrickkx - 23 days ago 19
Javascript Question

JS: Difference between simple number array and Array.slice()

I just wanna ask what's the difference between normal number array:

[1,2,3,4,5,6]
and
[1,2,3,4,5,6].slice();




console.log([1,2,3,4,5,6].slice());
console.log([1,2,3,4,5,6]);





The result seems to be the same, but something changes. I want to know what exactly it is.

Answer

With slice() (without arguments) function you create shallow copy of the original array.

var arr = [1,2,3,4,5,6];
arr === arr; // true
arr === arr.slice(); // false

It may be helpful when you want to clone some array, do some operation on it but not modify original one.

Comments