seeking some advice for my JavaScript code.
Everytime I console log num2 it still comes up as 5? Does it relate to the data type? Any reason as to why?
let num1 = 5;
let num2 = num1;
num1 = 8
console.log(num2);
I expected the number to change.
seeking some advice for my JavaScript code.
Everytime I console log num2 it still comes up as 5? Does it relate to the data type? Any reason as to why?
let num1 = 5;
let num2 = num1;
num1 = 8
console.log(num2);
I expected the number to change.
2
Answers
primitive types :
b copies a’s value at assignment. Changing a later doesn’t affect b.
For reference types:
obj1 and obj2 reference the same object, so a change through obj1 is seen via obj2.
let num2
is a variable that references something (whatever you point it to) and when you define it here you point it to the primitive number 5 (because that’s what’s inside ofnum1
at the moment).Later on, you change what the
num1
variable points to and instead point it to refer to a new primitive (8), but that doesn’t affectnum2
or the same old 5 that it still points to.