-5

i use this code snippet to make a copy of my user array :

var prevUsers = [...users];

but using "var prevUsers = users;" not working as well, and i want to know what is difference between these syntaxes ??

i checked prevUsers = [...users] & prevUsers = users with console.log but they return same results! i want to know why prevUsers = [...users] works but prevUsers = users not works ...

thanks to everyone

Amin Zekri
  • 21
  • 2
  • depends if `users` is an actual Array, or something that is "Array-like", or just an *iterable* .... `var prevUsers = [...users];` is a bit like `var prevUsers = Array.from(users);` except it's not the same, to be clear - it's a new Array for a start, not a reference to an existing array – Bravo Aug 18 '21 at 06:59
  • There are dozens and dozens of exemples explaining these kind of stuff https://stackoverflow.com/questions/31048953/what-does-the-three-dots-notation-do-in-javascript – Alexandre Elshobokshy Aug 18 '21 at 07:00
  • Does this answer your question? [What does the three dots notation do in Javascript?](https://stackoverflow.com/questions/31048953/what-does-the-three-dots-notation-do-in-javascript) – Mahyar Mottaghi Zadeh Aug 18 '21 at 07:09
  • @AminZekri I think you can find your answer below. Best of luck :) – Mahyar Mottaghi Zadeh Aug 18 '21 at 07:34

1 Answers1

1

It seems that your question consists of two sub questions:

  1. why "var prevUsers = users;" doesn't work
  2. what is the difference between "var prevUsers = users;" and "var prevUsers = [...users];"

I would need a little more detail (e.g., full code) to answer the first, but I can provide one for the second.

See the code below:

// creating array users
let users = [1, 2, 3, 4, 5];

// assigning users to prevUsers
var prevUsers = users;
console.log(prevUsers);

// modifying (deleting first element of) users
users.splice(0, 1);
console.log(prevUsers);
console.log(users);

You can see that assigning users to prevUsers is actually not a good practice because it is assigning the reference to the location of the users array, not creating a new array with identical content. Here's where the spread operator (...) comes in to play:

// creating array users
let users = [1, 2, 3, 4, 5];

// creates new array with the content from users and assigns to prevUsers
var prevUsers = [...users];

// modifying (deleting first element) users
users.splice(0, 1);
console.log(prevUsers);
console.log(users);

Using the spread operator, you can create a new array, place the elements of users inside it, and then assign the new array to prevUsers. Since the two arrays are different arrays, "users.splice(0, 1);" will not affect elements inside prevUsers.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Heon Yim
  • 33
  • 4