MATH OBJECT IN JAVASCRIPT

JS

The “Math object in JavaScript” allows you to perform mathematical operations on numbers. Unlike other objects, Math does not have a constructor as it is static. All methods and properties can be used without first creating the object.

METHODS OF MATH

The syntax for almost all Math methods is as follows: Math.method (number). There are 4 common methods to round a number to an integer:

Integer converter

MATH OBJECT IN JAVASCRIPT THE METHODS

Methods object Math
Copy to Clipboard

RANDOM METHOD OF THE MATH OBJECT

Math.random() used with Math.floor() can be used to return random integers.

// Returns a random integer from 0 to 9:
Math.floor(Math.random() * 10);

// Returns a random integer from 0 to 10:
Math.floor(Math.random() * 11);

// Returns a random integer from 0 to 100:
Math.floor(Math.random() * 101);

// Returns a random integer from 1 to 10:
Math.floor(Math.random()10) + 1;

// Returns a random integer from 1 to 100:
Math.floor(Math.random() * 100) + 1;

As you can see from the examples above, it might be a good idea to create an appropriate random function to use for all purposes of generating random integers. This JavaScript function always returns a random number between min (inclusive) and max (excluding):

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (maxmin) ) + min;
}

This JavaScript function always returns a random number between min and max (both included):

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (maxmin + 1) ) + min;
}

LINKS TO PREVIOUS POST

THE JAVASCRIPT LANGUAGE

LINK TO THE CODE ON GITHUB

GITHUB