Common Mathematical Operations in JavaScript

Common math operations like addition, substraction, multiplication, division and modules can be done using JavaScript's mathematical operators.

// addition using plus `+` operator
1 + 9; // 10

// substraction using minus `-` operator
9 - 1; // 8
// multiplication using asterisk `*` operator
9 * 2; // 18

// division using backslash `/` operator
9 / 2; // 4.5
// To get integer result of division
Math.trunc(9 / 2); // 4

// modulus (remainder after division) using percentage `%` operator
9 % 2; // 1

// exponent or power of with double asterisk `**` operator
7 ** 2; // 49

JavaScript has an built-in object called Math for performing common mathematical operations.

// Find square root
Math.sqrt(64); // 8

// Get integer part of number
Math.trunc(1.25); // 1

// Nearest integer
Math.round(1.49); // 1
Math.round(1.5); // 2

// Absolute or value without sign
Math.abs(-12.2); // 12.2
Math.abs(2.2); // 2.2

Find a random number within range (inclusive)

function randomInRange(start, end) {
return Math.floor(Math.random() * (end - start + 1)) + start;
}

randomInRange(10, 100); // 34
randomInRange(100, 500); // 278

Find sum of elements in an array

function sumOfArray(array) {
return array.reduce((sum, i) => sum + i, 0);
}
const array = [1, 2, 3, 4, 5];
sumOfArray(array); // 15

Find average of elements in an array

function average(array) {
return array.reduce((sum, i) => sum + i, 0) / array.length;
}
const array = [1, 2, 3, 4, 5];
average(array); // 3
Last updated on Thu Jan 07 2021
Tags: