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
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.
You change the values but you don’t update the sum!
Method 1 :
Method 2 :
Method 2b :
Method 3 (as Konrad suggest a function too):
Alternative method to be complete:
Here you display the full operation…
You can use a function