Variables and basic calculations
Objective
Name intermediate values and use arithmetic to calculate an answer.
Name intermediate values and use arithmetic to calculate an answer.
Explanation
const declares a name that cannot be reassigned. let declares a name whose value can change. Both need a name and an initial value in these examples. Choose a name that describes what the value means.
Arithmetic operators include +, -, *, and /. Parentheses specify grouping. JavaScript normally uses Number for both whole and fractional numbers; very large integers are not always exact. Our beginner inputs stay small. Unlike Python, adding a string and number with + may join text, so keep the input types in mind.
Worked example
const minutes = 15;
const sessions = 3;
const total = minutes * sessions;
console.assert(total === 45);
Common mistakes
Assigning to a const name again fails. Using "2" instead of 2 can turn addition into text concatenation.
Guided practice
Calculate four sessions of twelve minutes. Use let for a counter you intend to update and const for fixed inputs.
Independent practice
Try the exercises linked below. Predict an answer before running code, and explain one boundary case in your own words.
Recap
Name intermediate values and use arithmetic to calculate an answer. Compare the result with your prediction and use small examples to explain any difference.