You've successfully subscribed to The Poor Coder | Hackerrank Solutions
Great! Next, complete checkout for full access to The Poor Coder | Hackerrank Solutions
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
How to square a number in javascript

How to square a number in javascript

The most basic way to square a number in JavaScript is to multiply the number my itself. But there's two more.

Beeze Aal
Beeze Aal

Squaring a number is basic Mathematics. You should be able to solve it easily. Anyways if you are just lurking around or finding some tricky way to do that. Here are 3 different ways on how to square a number in JavaScript.

1. Multiply the number by itself

The most basic way to square a number in both in mathematics and JavaScript is to multiply the number my itself.

It's similar to how you write it in Mathematics. In mathematics you write it as

5x5 = 25

In JavaScript, there is a slight difference, that is, the multiplication operator is * instead of x.

You just have to replace the x with * to do multiplication in JavaScript. Pretty simple!

5*5

The above code will print return 25.

Let us define a function to do that

function squared(number) { return number*number } 

Use case

console.log(squared(5))

2. Using exponentiation

I assume you are familiar with exponents and power. In mathematics we write something like this

This gives us 4.

Unfortunately my keyboard doesn't know how to write that small 2 at the top. I had to copy the number from google just to show you. That's troublesome! So we prefer to do it the easy way in JavaScript

In JavaScript, we write it as

2**2

Function definition

function squared(number) { return number**2 }

Use case is the same as above

console.log(squared(5))

Note: Though * means multiplication ** doesn't mean double multiplication. It's a convention for power in JavaScript.

3. Using the inbuilt math object

In JavaScript we have a inbuilt Math library which is very useful for various mathematical operations such as rounding of value, finding the value of PI, Square root etc

It also includes a power function. Since the function is inbuilt in Math object you don't have to define a function. Use case is as follows

console.log(Math.pow(8, 2))  // prints 64 which 8 to the power 2

That's it. You  have learnt all the 3 ways to square a number in JavaScript.

To know more about JavaScript Math library visit here.

Let me know in the comments if you have some other way of squaring a number in JavaScript.