The Simple Trick to Squaring Numbers in JavaScript!
Squaring a number is a basic mathematical operation that involves multiplying a number by itself. In JavaScript, there are several ways to perform this operation. This article will explore different methods to square a number and provide examples for each approach.
01. Math.pow()
Method
The Math.pow()
method is a built-in JavaScript function that can be used to raise a number to a specified power. To square a number, you raise it to the power of 2.
// Squaring a number using Math.pow()
const number = 5;
const squared = Math.pow(number, 2);
console.log(squared);
// Output: 25
Math.pow(number, 2)
raises the number to the power of 2, effectively squaring it.
02. Exponentiation Operator (**
)
The exponentiation operator (**
) is a more recent addition to JavaScript, providing a concise syntax for exponentiation. To square a number, you use this operator with an exponent of 2.
// Squaring a number using the exponentiation operator
const number = 5;
const squared = number ** 2;
console.log(squared);
// Output: 25
number ** 2
squares the number using the exponentiation operator.
Support our work: ButMeACoffee
Originally published at https://www.rustcodeweb.com on August 15, 2024.