DEV Community

Cover image for JS Math cheatsheet
Michael Sakhniuk
Michael Sakhniuk

Posted on

35 3

JS Math cheatsheet

Hi everyone!
Continuing to write about JavaScript, today

Here is a list of most usefull Math object methods. Math is an object with methods and props for mathematical calculations. Also, Math is not a constructor and every method is static.

More methods and information you can check on MDN

abs

Math.abs(x) — Returns the absolute (positive) value of x

Math.abs(25);       // 25
Math.abs(-2);       // 2
Math.abs(null);     // 0
Math.abs('');       // 0
Math.abs([]);       // 0
Math.abs([2]);      // 2
Math.abs([1,2]);    // NaN
Math.abs({});       // NaN
Math.abs('-1');     // 1
Math.abs('string'); // NaN
Math.abs();         // NaN
Enter fullscreen mode Exit fullscreen mode

round

Math.round(x) — The value of x rounded to its nearest integer

Math.round(20.49);     // 20
Math.round(20.5);      // 21
Math.round(-20.5);     // -20
Math.round(-20.51);    // -21
Enter fullscreen mode Exit fullscreen mode

ceil

Math.ceil(x) — Value of x rounded up to its nearest integer

Math.ceil(.95);    // 1
Math.ceil(4);      // 4
Math.ceil(7.004);  // 8
Math.ceil(-0.95);  // -0
Math.ceil(-4);     // -4
Math.ceil(-7.004); // -7
Enter fullscreen mode Exit fullscreen mode

floor

floor(x) — The value of x rounded down to its nearest integer

Math.floor( 45.95); //  45
Math.floor(-45.95); // -46
Enter fullscreen mode Exit fullscreen mode

max

max(x,y,z,...,n) — Returns the number with the highest value

Math.max(10, 20);   //  20
Math.max(-10, -20); // -10
Math.max(-10, 20);  //  20
Enter fullscreen mode Exit fullscreen mode

min

min(x,y,z,...,n) — Same for the number with the lowest value

Math.min(10, 20);   //  10
Math.min(-10, -20); // -20
Math.min(-10, 20);  //  -10
Enter fullscreen mode Exit fullscreen mode

pow

pow(base, exponent)base to the power of exponent

Math.pow(7, 2); // 49
Math.pow(8, 2); // 64
Math.pow(2, 8); // 256
Enter fullscreen mode Exit fullscreen mode

random

random() — Returns a random number between 0 and 1 (include 0 and exclude 1)

sqrt

sqrt(x) — Square root of x

Math.sqrt(9);  // 3
Math.sqrt(2);  // 1.414213562373095
Math.sqrt(1);  // 1
Math.sqrt(0);  // 0
Math.sqrt(-1); // NaN
Math.sqrt(-0); // -0
Enter fullscreen mode Exit fullscreen mode

More knowledge and experience you will find there:

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →