. Advertisement .
..3..
. Advertisement .
..4..
To get a square number, it requires you to take a number and multiply it by itself. The following article explains various methods to square a number in Javascript. The numbers should have a constant assigned to a specific variable or use a form dynamically.
How To Square A Number In Javascript
Method 1: Use The Math.pow() Method
Using the Math.pow()
is one of the best ways to square a number. This one involves taking a number and raising it to a power. This power is equal to 2 when you square it.
The method takes two parameters, including the number of self-multiplying times and the target value or variable. A number’s exponent value means the number multiplied X times by this one.
Code:
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
Method 2: Use The Exponentiation Method
In Javascript, you can easily get the exponentiation operator with two asterisk symbols **
. This operator will take two numbers and return the first one raised to the second number’s power.
This a ** b
method tends to return the same result as the one of the Math.pow()
function. Your given equation will be a ** 2
.
Code:
function squareMyNumber(no){
return no ** 2
}
let squared = squareMyNumber(5);
console.log(" 5 ** 2 = ",squared);
Output:
5 ** 2 = 25
Method 3: Use The bigInt() Library
The BigInteger.js library is another method this article wants to introduce to you. It is a primitive wrapper object, which represents and manipulates bigint values. Those values are often too large to let the number primitive represent them.
You need to import the CDN library to perform a square operation with this method.
<script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.40/BigInteger.min.js"></script>
After that, here is the code for the squaring process:
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
Method 4: Create A Helper Function
Creating a helper function also allows you to square a number in Javascript. A helper function can perform another one’s computation, which offers descriptive names and makes your program easy to read. Here is the code to create this function:
function square(num){
return num * num;
}
The following code will help you find the square of a given number while reducing repetition and making the code cleaner:
console.log(square(2)); // 4
console.log(square(5)); // 25
console.log(square(8)); // 64
Conclusion
How to square a number in Javascript? We bet that after flicking through the article, you have got the best answer. There are various methods to choose from, so pick a suitable one for your number.
Leave a comment