JavaScript - Cheat sheet
Number constants #
Here are some of the built-in number constants that exist on the Math object:
The PI number:
Math.PIThe Euler’s constant:
Math.EThe natural logarithm of 2:
Math.LN2
Rounding methods #
These include:
Math.ceil()- rounds up to the closest integerMath.floor()- rounds down to the closest integerMath.round()- rounds up to the closest integer if the decimal is.5or above; otherwise, rounds down to the closest integerMath.trunc()- trims the decimal, leaving only the integer
Arithmetic and calculus methods #
Here is a non-conclusive list of some common arithmetic and calculus methods that exist on the Math object:
Math.pow(2,3)- calculates the number2to the power of3, the result is8Math.sqrt(16)- calculates the square root of 16, the result is 4Math.cbrt(8)- finds the cube root of 8, the result is 2Math.abs(-10)- returns the absolute value, the result is 10Logarithmic methods:
Math.log(),Math.log2(),Math.log10()Return the minimum and maximum values of all the inputs:
Math.min(9,8,7)returns 7,Math.max(9,8,7)returns 9.Trigonometric methods:
Math.sin(),Math.cos(),Math.tan(), etc.
Examples #
Random Method : #
A part of math object that can generate a number between 0 and 0.99
var decimal = Math.random();
console.log(decimal);
console.log(decimal * 10); // log the value of decimal multiplied by 10Ceil Method : #
A part of the math object that rounds a decimal up to the nearest integer.
var rounded = Math.ceil(0.0001);
console.log(rounded);
var rounded = Math.ceil(0.5);
console.log(rounded);
var rounded = Math.ceil(0.09);
console.log(rounded);
var rounded = Math.ceil(1.01);
console.log(rounded);
var rounded = Math.ceil(1.5);
console.log(rounded);
var rounded = Math.ceil(2.99);
console.log(rounded);Random Integer : #
var decimal = Math.random() * 10;
var rounded = Math.ceil(decimal);
console.log(rounded);