JavaScript - Cheat sheet

1 min read

Number constants

Here are some of the built-in number constants that exist on the Math object:

  • The PI number: Math.PI

  • The Euler’s constant: Math.E

  • The natural logarithm of 2: Math.LN2

Rounding methods

These include:

  • Math.ceil() - rounds up to the closest integer

  • Math.floor() - rounds down to the closest integer

  • Math.round() - rounds up to the closest integer if the decimal is .5 or above; otherwise, rounds down to the closest integer

  • Math.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 number 2 to the power of 3, the result is 8

  • Math.sqrt(16) - calculates the square root of 16, the result is 4

  • Math.cbrt(8) - finds the cube root of 8, the result is 2

  • Math.abs(-10) - returns the absolute value, the result is 10

  • Logarithmic 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 10

Ceil 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);

Thanks for reading !!! 😊
Share this post :

Common Questions in Angular