Practice Questions
1. What is the value of age
after this code runs?
Code Example:
let age = 10;
age + 2; // ❎ This does nothing since the result is not stored.
age = age + 2; // ✅ Correct way to update the value of 'age'
In JavaScript, the =
sign is known as the assignment operator. Its purpose is to take the value on the right-hand side of the equation and store it in the variable on the left-hand side.
After the code executes:
- The value of
age
becomes12
becauseage = age + 2
assigns the new calculated value back toage
.
Explanation:
The first statement age + 2;
does not modify age
because the result is not assigned to a variable. Only the second statement updates the value of age
.
2. What is the value of avg
after this code runs?
Code Example:
let num1 = 10;
let num2 = 20;
let avg = (num1 + num2) / 2;
Explanation:
The
avg
variable calculates the average ofnum1
andnum2
.First, the sum of
num1
andnum2
is calculated:10 + 20 = 30
.Then, the result is divided by
2
:30 / 2 = 15
.
So, the value of avg
is 15
.
Key Points:
Parentheses
()
ensure the addition operation is performed before division, following the operator precedence rules.Always remember to use proper grouping when working with complex calculations.
Program Output:
console.log(avg); // Output: 15