I have a variable arg and it has been assigned as follows
arg = [...arg];
What does this assignment mean ?
I have a variable arg and it has been assigned as follows
arg = [...arg];
What does this assignment mean ?
Assuming the original arg
is an array
What happens here is best demonstrated using an example
const x = [1,2,3,4];
const y = [...x];
x == y; // false
x === y; // false
x[0] == y[0]; // true
x[0] === y[0]; // true
So while the content of the array has remained identical, the array itself is another reference. So this created a copy of the array so the original array is not modified.
An example of this can be in a method
function example1(x) {
x = [...x];
x[0] = 0;
return x;
}
function example2(x) {
x[0] = 0;
return x;
}
const a = [1,2,3];
console.log(a);
const b = example1(a);
// The input variable is not mutated
console.log(a); // [1,2,3]
console.log(b); // [0,2,3]
const c = example2(a);
// The input variable is mutated as well
console.log(a); // [0,2,3]
console.log(c); // [0,2,3]