Today we are going to look at a case where you need to convert number X to a power of Y in JavaScript.

There are several options: using the standard ways of the language, and writing your own function.

Math.pow()

Math.pow(base, exponent)
base — число, которое возводится в степень
exponent — степень, в которую нужно возвести

// Let's take the number 5 to the second power
const result = Math.pow(5, 2);
console.log(result); // print 25

Operator ** (ES6)

With the advent of the ES6 standard, it is now possible to perform exponentiation with this operator – **

const result = 5 ** 2;
console.log(result);
// or
let pow = 5;
pow **= 2;

This is probably the simplest option today.

Exponentiation function using a cycle

If the options described above do not suit you, you can write your own function (most often this is simply required at job interviews or for some tests).

function pow(a, b) {
  let result = a;
  for (let i = 1; i < b; i++) {
    result *= a;
  }
  return result;
}
0 Shares:
Leave a Reply

Your email address will not be published.

You May Also Like