JavaScript - 3

JavaScript - 3: Numbers and Math Operations

JavaScript can work with numbers and perform calculations using familiar math operators.

In this lesson, you will create two number variables and use JavaScript to add, subtract, multiply, and divide them.

Your challenge: Use the variables a and b to calculate four different results and print each one with console.log().

✦ JavaScript Editor
▶ Live Output

JavaScript math operators

JavaScript uses symbols called operators to perform calculations.

The four operators in this lesson are:

+ for addition
- for subtraction
* for multiplication
/ for division

For example: console.log(a + b); adds the values stored in a and b.

With the starter values of 12 and 5, the result is 17.

Print a label with the result:

Instead of printing only the number, you can pass more than one value to console.log().

For example: console.log("Addition:", a + b);

This makes the output easier to understand because it tells you what the number represents.

Try all four calculations:

Use separate console.log() statements for addition, subtraction, multiplication, and division.

With a = 12 and b = 5, you should see results for all four operations in the Live Output.

Experiment with the numbers:

Change a from 12 to 20. You should not need to change any of your calculation statements.

They automatically use the new value stored in the variable.

JavaScript can produce decimal results:

The calculation: 12 / 5 does not divide evenly, so JavaScript returns a decimal result.

Try changing the numbers to: a = 20; and b = 4; and compare the division result.

Order of operations matters:

JavaScript follows familiar math rules when an expression contains several operators.

For example: 2 + 3 * 4 produces 14 because multiplication happens before addition.

Parentheses let you control which calculation happens first: (2 + 3) * 4 produces 20.

Try storing a result:

A calculation can also be saved in another variable: let total = a + b;

Then you can print it with: console.log(total);

This becomes useful when a calculated value needs to be reused later in a program.

Extra experiment: Create a variable called price and another called quantity. Multiply them together to calculate a fictional total cost.

Good JavaScript habit: Use clear variable names when the numbers represent something specific. Names such as price and quantity usually explain more than names such as a and b.

👀 Show Solution
let a = 12;
let b = 5;

console.log("Addition:", a + b);
console.log("Subtraction:", a - b);
console.log("Multiplication:", a * b);
console.log("Division:", a / b);

Each statement uses the same two variables with a different math operator. Because the values are stored in variables, changing a or b automatically changes all four results.