There are a bunch of ways we can use JavaScript to square a number. The first method we will go over is using the JavaScript exponentiation operator, **.

```
var squaredNumber = 6**2;
console.log(squaredNumber);
#Output
36
```

The exponentiation operator will simply take the first number, and raise it to the power of the second number. **So to square a number, we simply need to make sure the second number is 2**.

Here are more examples of squaring numbers using the exponentiation operator.

```
var squaredNumber1 = 0**2;
var squaredNumber2 = 1**2;
var squaredNumber3 = 2**2;
var squaredNumber4 = 3**2;
var squaredNumber5 = 4**2;
var squaredNumber6 = (-5)**2;
console.log(squaredNumber1);
console.log(squaredNumber2);
console.log(squaredNumber3);
console.log(squaredNumber4);
console.log(squaredNumber5);
console.log(squaredNumber6);
#Output
0
1
4
9
16
25
```

Notice when squaring a negative number, we must put it in parenthesis, (-5).

Let’s look at another way to square a number using JavaScript.

## Using JavaScript to Square a Number Using the Math.pow() Method

We can also square a number by using the Math.pow() method.

```
var num = Math.pow(2,2);
console.log(num);
#Output
4
```

Just like with the exponentiation operator, the **Math.pow()** method will simply take the first number, and raise it to the power of the second number. So to square a number, we simply need to make sure the second number is 2.

Here are our examples again using the Math.pow() method.

```
var squaredNumber1 = Math.pow(0,2);
var squaredNumber2 = Math.pow(1,2);
var squaredNumber3 = Math.pow(2,2);
var squaredNumber4 = Math.pow(3,2);
var squaredNumber5 = Math.pow(4,2);
var squaredNumber6 = Math.pow(-5,2);
console.log(squaredNumber1);
console.log(squaredNumber2);
console.log(squaredNumber3);
console.log(squaredNumber4);
console.log(squaredNumber5);
console.log(squaredNumber6);
#Output
0
1
4
9
16
25
```

Let’s look at one final way to square a number using JavaScript.

## Using JavaScript to Square a Number By Creating a Function

One final way we will look at using JavaScript to square a number is by simply making our own function. **To square a number, we simply need to multiply it to itself**. So let’s make a simple function to do this.

```
function squareNumber(num){
return num*num;
};
```

And that’s it. Let’s test our method with the same examples from above.

```
function squareNumber(num){
return num*num;
};
console.log(squareNumber(0));
console.log(squareNumber(1));
console.log(squareNumber(2));
console.log(squareNumber(3));
console.log(squareNumber(4));
console.log(squareNumber(-5));
#Output
0
1
4
9
16
25
```

Hopefully this article has been useful in helping you learn how to use JavaScript to square a number.

## Leave a Reply