Arithmetic Operations

JavaScript can also calculate. For the basic arithmetic operations, it uses these operators (symbols for operations):

  • + addition
  • - subtraction
  • * multiplication (an asterisk, or star, because there is no × on the keyboard)
  • / division (a slash instead of ÷)

When you put a calculation in console.log(), it prints the result:

console.log(10 + 1);
console.log(7 * 6);
console.log(10 - 5 / 5);

This prints:

11
42
9

Why is the last result 9 and not 1? Just like in math, multiplication and division are done before addition and subtraction. So JavaScript first calculates 5 / 5, which is 1, and then 10 - 1, which is 9. Operations of the same level, such as + and -, are done from left to right. If you want a different order, use parentheses, again as in math:

console.log((10 - 5) / 5);

This prints 1: first 10 - 5 in the parentheses, then 5 / 5.

The spaces around the operators don't change the result. We write them because they make the code easier to read.

Careful with quotes: anything in quotes is text, and text is printed exactly as it is written, without calculating anything:

console.log("10 - 5 / 5");

This prints:

10 - 5 / 5

You can also print several values at once: separate them with commas inside the parentheses. console.log() prints them on one line, with a space between them. This is handy for printing a calculation together with its result:

console.log("10 - 5 / 5 =", 10 - 5 / 5);

This prints:

10 - 5 / 5 = 9

The first value is text, so it is printed as it is written. The second one is a calculation, so its result is printed.

Instructions

Print the result of 2 + 3 * 4. Before you click Run, guess what it will print.

On the next line, print the result of the same calculation, but with parentheses that make the addition come first: (2 + 3) * 4.

On the next line, print the calculation and its result on one line, like this:

(2 + 3) * 4 = 20

Write the calculation in quotes as the first value, then a comma, and then the calculation itself, without quotes.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

2/15

Next