Reputation: 3
I don't understand what the difference is betwee
const arrCopy = arr;
and
const arrCopy = [...arr];
Upvotes: 0
Views: 88
Reputation: 2699
One of the use cases (react context):
const UserList = () => {
const [users, setUsers] = useState([]);
...
const addUser = (newUser) => {
users.push(newUser);
// setUsers(users); <== won't work
setUsers([...users]);
}
....
return <UserListRenderer items={users} />
}
Upvotes: 0
Reputation: 3805
In JavsScript, arrays and objects are held by reference. This means:
const arr1 = ['a', 'b', 'c'];
const arr2 = arr1;
console.log(arr1 === arr2); // true
arr2.push('d');
// arr2 and arr1 = ['a', 'b', 'c', 'd'];
With the second method (a shallow clone), the arrays are both still references, but the value is taken instead:
const arr1 = ['a', 'b', 'c'];
const arr2 = [...arr1];
console.log(arr1 === arr2); // false
arr2.push('d');
// arr1 = ['a', 'b', 'c']; arr2 = ['a', 'b', 'c', 'd'];
Just know with this that any objects or arrays inside of the array are still held by reference:
const arr1 = [1, [2, 3], [4, 5]];
const arr2 = [...arr1];
arr2.shift();
arr2[0].push('test');
// arr1 = [1, [2, 3, 'test'], [4, 5]];
// arr2 = [[2, 3, 'test'], [4, 5]]
The older (non-ES6) method of shallow clones was arr1.slice()
.
Upvotes: 0
Reputation: 190941
In the first case, you are giving the instance of an array a new name. In the second with the spread operator, you are creating a new array with a copy of the items within the original, but it doesn't do a deep copy.
const arr = [1, 2, 3];
const anotherArr = arr;
console.log(arr === anotherArr);
const copyArr = [...arr];
console.log(arr === copyArr);
Upvotes: 1