skip to Main Content

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


  1. primitive types :

    let a = 10;
    let b = a;
    a = 20;
    
    console.log(b); // 10
    

    b copies a’s value at assignment. Changing a later doesn’t affect b.

    For reference types:

    let obj1 = { value: 10 };
    let obj2 = obj1;
    obj1.value = 20;
    
    console.log(obj2.value); // 20
    

    obj1 and obj2 reference the same object, so a change through obj1 is seen via obj2.

    Login or Signup to reply.
  2. 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 of num1 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 affect num2 or the same old 5 that it still points to.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search