Understand Math

Math

Arithmetic Operators

Arithmetic operators takes numbers and returns the result of the math operation.

Addition (+)

The plus sign adds together two numbers. Note that the same plus sign will concatenate two strings.

console.log(3 + 4);
// prints 7

Subtraction (-)

The minus sign subtracts one number from another.

console.log(8 - 2);
// prints 6

Multiplication (*)

The star sign multiplies two numbers.

console.log(3*5);
// prints 15

Division (/)

The slash sign returns the result of division.

console.log(20/5);
// prints 4

Increment Operator (++)

The ++ code adds one.

let aNumber = 354;
console.log(aNumber);
aNumber++;
console.log(aNumber);

Decrement Operator (--)

The -- code subtracts one.

let someNumber = 43;
console.log(someNumber);
someNumber--;
console.log(someNumber);

Properties & Methods

Property

Universal constants like e and pi are capitalized as JavaScript properties.

Math.E

Math.E is euler's number.

console.log(Math.E);
// prints 2.718281828459045...

Math.PI

Math.PI is the value of pi.

console.log(Math.PI);
// prints 3.141592653589793...

Methods

Math.random()

Math.random() produces a random number between 0 and 1. The result of Math.random() includes 0 and excludes 1.

console.log(Math.random());
// prints something different each time for example: 0.7081166606902392

Math.round(x)

Math.round(x) rounds to the nearest integer.

console.log(Math.round(6.8414));
// prints 7

Math.floor(x)

Math.floor(x) rounds down to the integer below.

console.log(Math.floor(6.8414));
// prints 6

Math.ceil(x)

Math.ceil(x) rounds up to the integer above.

console.log(Math.ceil(6.1414));
// prints 7

Math.abs(x)

Math.abs(x) returns the absolute value of x.

console.log(Math.abs(-25));
// prints 25

Math.log10(x)

Math.log10(x) returns the base 10 logarithm of a number.

console.log(Math.log10(100));
// prints 2