Course Content
Introduction to JavaScript
Introduction to JavaScript
Performing Arithmetic On Variables
We can perform arithmetic on variables storing numbers similar to how we perform operations on raw numerical values.
For example:
let varA = 10; let varB = 20; console.log(varA + varB);
The expression varA + varB
considers varA
and varB
as if they were raw numbers.
The right-hand side of the assignment statement is always evaluated before feeding the result into the variable on the left side. Because of this, we can make changes to the value of a variable:
let exampleVar = 100; console.log(exampleVar); // Before exampleVar = exampleVar + 100; console.log(exampleVar); // After
This above code adds 100 to the value of exampleVar
.
However, the same operation can also be performed using a shorter syntax:
let exampleVar = 100; exampleVar += 100; console.log(exampleVar);
This syntax works for any supported arithmetic operation.
For example:
exampleVar *= 100; // Multiplication exampleVar /= 100; // Division exampleVar **= 100; // Raising to a Power exampleVar %= 100; // Remainder
A short syntax for incrementing the value of a variable by 1
is by using the ++
operator. For-example:
let varA = 9; console.log(varA); // Before varA++; console.log(varA); // After
We can use --
for decrementing a variable by 1
:
let varA = 5; console.log(varA); // Before varA--; console.log(varA); // After
1. What will the following code output?
2. What is the purpose of the following line of code?
3. Which of the following is the correct shorthand for the operation exampleVar = exampleVar - 50
?
4. What will the following code output?
Thanks for your feedback!