I am learning to code and trying out some JavaScript programming and came across this which I don't understand. Please help! I don't understand why it wouldn't add the number with '+' but does with '+='.
let number = 10;
number + 10; //Return 10
number += 10; //Return 20
console.log(number);
There is an important distinction to make between and expression and an instruction. An expression evaluates to a value, but doesn't necessarily have an effect. An instruction doesn't necessarily evaluate to a value, but has some effect.
In your example, number + 10 is an expression that evaluates to 20. But it has no effect by itself.
By contrast, number += 10 is an instruction that modifies the value of variable number.
Note that number += 10 is essentially equivalent to number = number + 10.
The last line in your code, console.log(number), is also an instruction: it prints the value of number.
Have you tried the instruction console.log(number + 10)?
'+=' operator come from C language and it's a shortcut for
number = number + 10
so in your code all works,
but number + 10 is just operation without assignment;
The line number + 10 will calculate the value but you need to assign this value to the variable (to store it in the variable).
Indeed, you need to write number = number + 10.
About the syntax += : It only makes the code easier to read, the two following make exactly the same thing :
number = number + 10number += 10For more informations Addition assignment