Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

4.1 - Math with Arithmetic Operators

arithmetic operators

There are multiple ways we can operate on numbers, just like in math!

OperatorMeaningExample
+Addition: Adds two valueslet add = 250 + 170;
-Subtraction: Minuses one value from anotherlet sub = 500 - 80;
*Multiplication: Multiplies two numberslet mul = 5 * 8;
/Division: Divides one number by anotherlet splitCandy = 100 / 12;
%Modulo: Returns the remainder of dividing one number by anotherlet leftOverCandy = 100 % 12;

the modulo % operator

The modulo operator is a little complicated when first seeing it, but once you understand that it's all about remainders, it's not so bad!

x = 21;
console.log(x % 4); // 21 ÷ 4 = 5 remainder 1, so this will print 1

Another big use for the modulo operator is by checking whether a number is odd or even. We can do this by doing x % 2 - an odd number has a remainder when divided by 2, whilst an even number has no remainder!

your turn: arithmetic operators task

  1. Create two number variables x, y and set it to any value you like!
  2. Print the value of x added to y
  3. Print the value of x and y multiplied together
  4. Print the value of x divided by y
  5. Print the remainder when x is divided by y