In a Mozilla developer translated Korean lang says 'slice method' returns a new array copied shallowly.
so I tested my code.
var animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
var t = animals.slice(2,4);
console.log(t);
t[0] = 'aaa';
console.log(t);
console.log(animals);
but, If slice method returns shallow array, the animals array should be changed with ['ant', 'bison', 'aaa', 'duck', 'elephant'].
Why is it shallow copy?
slice is a shallow-copy method, which means it can't copy an object deeply.
The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.
slice does not change original array it return new array but splice changes the original array.
slice() is a method of Array Object and String Object. It is non-destructive since it return a new copy and it doesn't change the content of input array.
strings are primitive types in JavaScript, so you will get a new array with new strings inside.
Your test array should be an array of objects:
var animals = [{name: 'ant'}, {name: 'bison'}, {name: 'camel'}, {name: 'duck'}, {name: 'elephant'}];
var t = animals.slice(2,4);
console.log(t);
t[0].name = 'aaa';
console.log(t);
console.log(animals);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With