-1

I am having difficulty understand this behavior in Javascript. I am trying to assign a value to this.val, when I try to assign it a value using a variable, it does not assign successfully...

Example 1)

class TestVariableAssignment {
    constructor() {
        this.val = null;
    }

     assign() {
        let value = this.val;
        value = 5;
        console.log(this.val); // null
    }
}

const testVariableAssignment = new TestVariableAssignment();

testVariableAssignment.assign();

Example 2) this one seems to assign this.val a value correctly though ....

class TestVariableAssignment {
    constructor() {
        this.val = null;
    }

    assign() {
        this.val = 5;
        console.log(this.val); // 5
    }
     
}

const testVariableAssignment = new TestVariableAssignment();

testVariableAssignment.assign();

Why does this occur? Can someone why Example 1 does not work but example 2 does? Why can I not update this.val while using a variable?

Simone Anthony
  • 352
  • 4
  • 12
  • 2
    JS is not pass-by-reference. It's pass-by-value. Reassigning a variable changes its value, that's it. It doesn't change whatever was assigned to it. – VLAZ May 19 '22 at 13:06

0 Answers0