Square a Number in JavaScript

  1. Use the Math.pow() Method to Square a Number in JavaScript
  2. Use the Exponentiation Method to Square a Number in JavaScript ECMAScript 6
  3. Use the bigInt() Library to Square a Number in JavaScript

This article will explain how to square a number in JavaScript in multiple ways.

Use the Math.pow() Method to Square a Number in JavaScript

One way to square a number in JavaScript is to use the pow() method from the Math library. The function takes two arguments: the first one is our target variable or value, and the second is the number of times we want to multiply it by itself. In case we want to square that number, we will send 2 as the second argument.

let squaredNumber = Math.pow(5,2);
console.log("5*5 = ",squaredNumber);

let variable = 5 ;
let squaredNumber2 = Math.pow(variable,2);
console.log("5*5 = ",squaredNumber2);

Output:

5*5 =  25
5*5 =  25

Use the Exponentiation Method to Square a Number in JavaScript ECMAScript 6

Another way to square a number in JavaScript ECMAScript 6 is to use the Exponentiation method. The method a ** b returns the same result as the Math.pow function. To square a number with ES6 Exponentiation, our equation would be a ** 2.

function squareMyNumber(no){
    return no ** 2
}

let squared = squareMyNumber(5);
console.log(" 5 ** 2 = ",squared);

Output:

 5 ** 2 =  25

Use the bigInt() Library to Square a Number in JavaScript

The last way we want to explain in his tutorial is how to use the BigInteger.js library to perform a square operation to a number in JavaScript. We need to import the library CDN as the following.

<script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.40/BigInteger.min.js"></script>

Then, we can use it like that:

function squareMyNumber(no){
    return bigInt(no).square()
}

let squared = squareMyNumber(5);
console.log("square of 5 using bigInt library= "+squared);

Output:

26593302.js:13 square of 5 using bigInt library= 25
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.