How to Square a Number in Javascript
|

How to Square a Number in Javascript

Want to square a number in javascript? Just take the number and multiply it by itself using the multiplication operator (*)! However, there are three different ways to compute the square of a number in javascript.

1- Multiplication (*) operator

Arithmetic operators are available in javascript. Arithmetic operators perform arithmetic on numbers (literals or variables). The (*) operator is used to multiply numbers. You can use the (*) operator and multiply the number by itself.

let sqNum = 5 * 5;
console.log(sqNum); // 25

2- Math.pow()

The Math.pow() method returns the value of a base raised to a power.

// syntax
// Math.pow(base, exponent)

let sqNum = Math.pow(5, 2);
console.log(sqNum); // 25

3- Exponentiation (**) operator

The exponentiation (**) operator returns the result of raising the first operand to the power of the second operand. It is equivalent to Math.pow(), except it also accepts BigInts as operands.

let sqNum = 5 ** 2;
console.log(sqNum); // 25

Related articles:

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *