Global objects defined by Javascript Date and Math


Published on 06 April 2022


Global objects defined by Javascript Date and Math

Objects defined by Javascript Date & Math

Date.

The Date object allows us to do operations with dates.
First we create a variable that stores a new date.
In this case it will show us the current system date:

var date = new Date();

If we want to display the current year from the created date variable:

var year = date.getFullYear();

If we want to show the current month or day:

var month = date.getMonth();
var day = date.getDate();

console("Today is month " + month + ", day " + day + ", year " + year);

Math.

The Math object is a default global Javascript object that allows us to do numerous mathematical operations.
To use it, simply write within our Math script followed by a period and its many options that allow us to perform different operations.

Modes of use:
Find the smallest number in a series of numbers:
console.log(Math.min(1,2,3,10));
Find the largest number in a series of numbers:
console.log(Math.max(1,2,3,10));
Round a decimal number:
console.log(Math.round(7.4));
Round a decimal number down:
console.log(Math.floor(7.4));
Round a decimal number up:
console.log(Math.ceil(7.4));
Show a random number:
console.log(Math.random());

In the following example we will create a function that will generate a random number up to a maximum number that we will choose randomly, in this case 20, resulting in a rounded number:

function genRandom(numberMax){
  return Math.round(Math.random() * numberMax);
}
console.log(genRandom(20));

The nomenclature (Math.random() * numberMax) refers to a random number taking as maximum numberMax.


Previous Chapter - Next Chapter



Tips on SEO and Online Business

Next Articles

Previous Articles