Using Math in Javascript

Simple operations with integers

JavaScript has math operators built in. This means that you don't have to import a library just to add some numbers. You can do all the operations as expected.

let a = 7 + 5
let b = 15
let c = b+a
console.log (c) //Expected output: 27
console.log (b*a) //Expected output: 180

You can use all basic operations, and can even use addition to join strings together. This isn't the best way to join strings together, but it is commonly used as it is very simple.

const userName = 'Jeff'
let greet = 'Welcome ' + userName + '!' console.log (greet)
//Expected output: Welcome Jeff!

Using the Math object

JavaScript has a built-in Math object, which you can use to do more complex mathemactical operators. This object is very commonly used, and can do think like round numbers and pick random numbers from a certain range. In this article, we will only go in depth with picking random numbers, rounding numbers and exponents.

Picking random numbers

It is very useful, especially when something has to be chosen in ranodom, not only numbers. the random function picks a number from 0-1, so if you have more than 2 options you have to multiply it by the number of options.

const randomNum = Math.random()
// Random picks a number from 1 to 0. Ex: 0.5417369
const randomNum2 = Math.random() * 10
//Picks a num from 0 to 10

This is still not ready, as the number could still have a decimal. How do we round it? Well, there are many different ways. You can do the normal rounding, where a integer goes to its closest value(.round), you can round down(.floor) or round up(.celi)

let rounded = Math.round(4.4)
//Returns 4
let rounded2 = Math.round(4.7)
//Returns 5
let rounded3 = Math.floor(14.7)
//Returns 14
let rounded4 = Math.celi(2.1)
//Returns 3

const random = Math.round(Math.random()*9)
//Picks an integer from 0-9, and then rounds it.
//Possible numbers: 0,1,2,3,4,5,6,7,8,9.

Other math types:

You can use many functions in JavaScript. Some useful ones include: sqrt(number), pow(num,exponent), and math.pi()


Read more about those methods here.