skip to Main Content

I updated the value of the variable val1, but the value 5 is still displayed in the console.

let val1 = 2
let val2 = 3
let sum = val1 + val2
console.log(sum) // 5
val1 = 3
console.log(sum) // 5

After changing the value of val1, I expected to see the updated value of the sum equal to = 6. But its old value of the sum was displayed. Why hasn’t the value been updated?

3

Answers


  1. You are printing the sum which has been already taken the value. So if you really want to updated sum of value val1 you could write your code like this.

    let val1 = 2
    let val2 = 3
    let sum = val1 + val2
    console.log(sum) // 5
    val1 = 3
    console.log(val1+val2) // 6
    Login or Signup to reply.
  2. You change the values but you don’t update the sum!

    Method 1 :

    let val1 = 2
    let val2 = 3
    let sum = val1 + val2 // do the sum of the values
    console.log(sum) // 5
    val1 = 3
    sum = val1 + val2 // redo the sum of the updated values
    console.log(sum) // 6
    // Or just
    console.log(val1+val2) // 6

    Method 2 :

    function sumFunction(a,b){
      return (a+b);
    }
    val1 = 2;
    val2 = 3;
    console.log(sumFunction(val1,val2)); //output 5
    val1 = 3;
    val2 = 3;
    console.log(sumFunction(val1,val2)); //output 6
    console.log(sumFunction(5,8)); // output 13

    Method 2b :

    val1 = 2;
    val2 = 3;
    console.log(sumFunction(val1,val2)); //output 5
    val1 = 3;
    val2 = 3;
    console.log(sumFunction(val1,val2)); //output 6
    console.log(sumFunction(5,8)); // output 13
    function sumFunction(a,b){
       return (a+b);
    }

    Method 3 (as Konrad suggest a function too):

    val1 = 4;
    val2 = 5;
    let sumArrowFunction = (a,b) => a + b;
    console.log(sumArrowFunction(val1,val2));
    console.log(sumArrowFunction(5,5));

    Alternative method to be complete:
    Here you display the full operation…

    val1 = 2;
    val2 = 1;
    console.log(calcFunction(val1,val2));
    console.log(calcFunction(12,3));
    function calcFunction(a,b){
       return (`${a}  + ${b}  =  ${a+b}`);
    }
    Login or Signup to reply.
  3. You can use a function

    let val1 = 2
    let val2 = 3
    let sum = () => val1 + val2
    console.log(sum()) // 5
    val1 = 3
    console.log(sum()) // 6
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search