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.
var num = 8; num * = num; // same as num = num * num; console.log(num); //64 //or var squareOfNum = num * num; console.log(squareOfNum); //64
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.
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.