Introduction To JavaScript Math
We continue in the Speedy Chef project folder throughout this section.
Introduction
This section will continue with our Speedy Chef project, but we are going to be focusing on some handy Math, Date, and timer functionality which JavaScript offers. Starting by looking at how we can use JavaScript Math to generate random pizzas and orders.
Currently we only have a set of three orders which is always the same, but we can generate new ones which are a bit more random, and these will keep coming in as the game is running.
New order and pizza functions
First create two new functions to do this, at the bottom of the script:
// index.js
// generates new orders with order numbers:
function generateNewOrder() {}
// generate random pizzas and quantities so each order is random, this function will be called by generateNewOrder above
function generateNewPizza() {}
To begin, log the value of the JavaScript Math object, in the generateNewPizza
function:
function generateNewPizza() {
// 1. log the Math object to the console
console.log(Math);
}
// 2. call function
generateNewPizza();
The Math object
You will see the Math object in the console:
Math {abs: ƒ, acos: ƒ, acosh: ƒ, asin: ƒ, asinh: ƒ, …}
E: 2.718281828459045
LN2: 0.6931471805599453
LN10: 2.302585092994046
LOG2E: 1.4426950408889634
LOG10E: 0.4342944819032518
PI: 3.141592653589793
SQRT1_2: 0.7071067811865476
SQRT2: 1.4142135623730951
abs: ƒ abs()
...
There are some constants we can use such as the value of PI
, which you may be familiar with. And some methods to help us out too. We have random
, to generate a random number, we have ceil
and floor
to round up and down, we will look at these soon.
There is a method to round to the nearest number, find the smallest and largest number with min
and max
, and many others.
Examples
Back to the function to try out some examples:
function generateNewPizza() {
console.log(Math.PI);
console.log(Math.random()); // 0 included, 1 not
console.log(Math.random() * 100); // 0-99
// store in constant then round up
const random = Math.random() * 100;
console.log(Math.ceil(random)); // 1-100
// round down
console.log(Math.floor(random)); // 0-99
// Find the largest number value:
const highest = Math.max(1, 77, 34);
console.log(highest); // 77
const lowest = Math.min(1, 77, 34);
console.log(lowest); // 1
// Both methods can also be used with negative numbers too.
// To find the highest/lowest value of an array, we need to spread the values into min/max:
const numbers = [1, 77, 34];
const highest = Math.max(...numbers);
console.log(highest); // 77
}
And next we are going to put this into practice by generating random pizzas and orders.