Ask coding questions

← Back to all posts
Setting a variable to another variable doesn't work.
Mathman05 (1)

when I do

a=[1,2,3,4,5]
b=a
b[1]="yes"
console.log(a[1])

it prints yes. how do I make it make a copy and not just modify a's value?
Edit: I found something that works quickly: b=a.concat([]);

Comments
hotnewtop
xxpertHacker (930)

Shallow copy:

a = [...b];

and make sure to declare your variables with let, otherwise, good luck.

notGilbert (121)

@xxpertHacker ... goes before the variable (spread syntax)

xxpertHacker (930)

@notGilbert I was pretty sure that it was wrong, but didn't really care to confirm.

Coder100 (18148)

Objects and arrays are passed by reference. Refer to my tutorial for a fix:
https://replit.com/talk/learn/Deep-Cloning-Objects/85177

OldWizard209 (1531)

you can do this buy setting b to an empty list and use a while loop to iterate over every item in a, and put it into b. What you did was setting b, to a, which makes both the same thing.

a = [1, 2, 3, 4, 5];
b = [];
n = -1;
listLength = a.length

while (listLength > ++n) {
  b[n] = a[n];
}

b[1] = "yes"

console.log(a[1])

Output: 2

Mathman05 (1)

@OldWizard209 yeah but I have very large lists... I found b=a.concat([]); works well

OldWizard209 (1531)

can you attach your repl. I will then tell you how to change your code. @Mathman05

OldWizard209 (1531)

well, what is wrong with using a while loop to change the array you want? or just follow @Coder100 's tutorial if that helps... Mathman05

Mathman05 (1)

@OldWizard209 it's too slow I made an edit to my post showing what found to work.