UX Design and Development course

Working with math objects

Javascript does math!

console.log(Math.PI); // JS KNOWS PI!

console.log(Math.E); // Euler

That's fun, but let's make this interactive

var number = prompt('Enter a number', '');
var answer = Math.sqrt(number);

Let's test to see if this is a number or not and send the correct reply

if (isNaN(answer)) {
  console.log('That is not a number dude!');
} else {
  console.log('The square root of ' + number + ' is ' + answer);
}

JavaScript provides eight mathematical constants that can be accessed from the Math object. Mathematical constant = an interesting number.

Other things we can do with math are ...

Round numbers

var roundNumber = Math.round(answer);
console.log('Rounded up is ' + roundNumber);

Max number

var topNumber = roundNumber;
var bottomNumber = roundNumber / 2;
var maxNumber = Math.max(topNumber, bottomNumber);

console.log('Top number is ' + topNumber + ', low number is ' + bottomNumber + ', so your max number is ' + maxNumber);

Min number

var topNumber = roundNumber;
var bottomNumber = roundNumber / 2;
var minNumber = Math.min(topNumber, bottomNumber);

console.log('Top number is ' + topNumber + ', low number is ' + bottomNumber + ', so your min number is ' + minNumber);

Random numbers

var randomNumber = Math.ceil(Math.random() * maxNumber);
console.log('Your random number is ' +  randomNumber);

For a full list of math methods https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math

Play with code

JS Bin