Looking for how to square a number in JavaScript? In this quick tutorial, you will learn three ways to do the square of any given number in Js with programming examples.

Using Multiplication Operator – Square a Number in JavaScript

As we know that we can square a number simply by multiplying the number with itself. For example : 2×2= 4 or 8×8=64.

Let’s write a basic JavaScript program using the multiplication (*) operator.

var num = 8;
num * = num;  // same as num = num * num;
console.log(num);  //64


var squareOfNum = num * num;
console.log(squareOfNum); //64

Using In-built Math.pow() Function – To Square a Number in JavaScript

We can also square a number using pow() function. This is an in-built function provided in the Math Class in JavaScript.

Math.pow() function is easy to use and simply accepts two parameters of type number. Syntax: Math.pow (baseNumber, magnitude);

Note: you need to use the (.) dot operator with the Math Class.

Here is a JavaScript code example to square a number.

var num = 8;
var squareOfNum = Math.pow(num,2);

console.log(squareOfNum); //64

The first parameter is the base number you want to square, for example, 8. The second parameter is the power or the magnitude of the base number. To get the square we need to always pass 2.

Using ES6 Exponentiation Operator – Square a Number in JS

If you use ECMA Script or ES6 then this is an alternative to the use of Math.pow() function.

The exponentiation (**) operator returns the result, raising the very first operand to the power of the second operand.

An advantage of using an Exponentiation operator is that it also accepts BigInt value.

let num = 8;
let squareOfNum = num**2;

console.log(squareOfNum); //64

Note: The Exponentiation is not supported in Internet Explorer (browser).

In conclusion, you can use any of the above ways to get the square of a number. Try to make it less complicated, We will always suggest the first way i.e simple multiplication.

However, if you are dealing with BitInt’s type then you have to use the exponentiation way to square a number in JavaScript.

You might be interested to read += operator in JavaScript 

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed