4.1 - Math with Arithmetic Operators
arithmetic operators
There are multiple ways we can operate on numbers, just like in math!
Operator | Meaning | Example |
---|---|---|
+ | Addition: Adds two values | let add = 250 + 170; |
- | Subtraction: Minuses one value from another | let sub = 500 - 80; |
* | Multiplication: Multiplies two numbers | let mul = 5 * 8; |
/ | Division: Divides one number by another | let splitCandy = 100 / 12; |
% | Modulo: Returns the remainder of dividing one number by another | let 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
- Create two number variables
x, y
and set it to any value you like! - Print the value of x added to y
- Print the value of x and y multiplied together
- Print the value of x divided by y
- Print the remainder when x is divided by y