McKayla
McKayla

Reputation: 6949

JavaScript exponents

How do you do exponents in JavaScript?

Like how would you do 12^2?

Upvotes: 108

Views: 86576

Answers (8)

dota2pro
dota2pro

Reputation: 7856

// Using Math.pow
console.log(Math.pow(12, 2)); // 144
// Using ES7
console.log(12**2); // 144
// Using Recursion
const power =(base, exponent) => {
  if (exponent === 0) return 1;
  return base * power(base, exponent - 1);
}
console.log(power(12,2)); // 144

Upvotes: 0

Jaspal Singh
Jaspal Singh

Reputation: 209

Math.pow function is deprecated

Math.pow(a,b)

So better to use the exponentiation assignment ** as:

a**b

Example:

const postMoneyValuationRevenue = Math.round(
      exitValueRevenue / (1 + returnRatePercentage / 100) ** exitYear,
    );

Upvotes: -4

Deepu Reghunath
Deepu Reghunath

Reputation: 9663

Working Example:

var a = 10;
var b = 4;

console.log("Using Math.pow():", Math.pow(a,b)); // 10x10x10x10
console.log("Using ** operator:", a**b);  // 10x10x10x10

You can use either Math.pow() or ** operator

Upvotes: 1

Mayank_VK
Mayank_VK

Reputation: 17

How we perform exponents in JavaScript
According to MDN
The exponentiation operator returns the result of raising the first operand to the power second operand. That is, var1 var2, in the preceding statement, where var1 and var2 are variables. Exponentiation operator is right associative: a ** b ** c is equal to a ** (b ** c).
For example:
2**3 // here 2 will multiply 3 times by 2 and the result will be 8.
4**4 // here 4 will multiply 4 times by 4 and the result will be 256.

Upvotes: -1

Salvador Dali
Salvador Dali

Reputation: 222511

There is an exponentiation operator, which is part of the ES7 final specification. It is supposed to work in a similar manner with python and matlab:

a**b // will rise a to the power b

Now it is already implemented in Edge14, Chrome52, and also it is available with traceur or babel.

Upvotes: 64

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

Math.pow():

js> Math.pow(12, 2)
144

Upvotes: 136

Anon Ymus
Anon Ymus

Reputation: 111

Math.pow(x, y) works fine for x^y and even evaluates the expression when y is not an integer. A piece of code not relying on Math.pow but that can only evaluate integer exponents is:

function exp(base, exponent) {
  exponent = Math.round(exponent);
  if (exponent == 0) {
    return 1;
  }
  if (exponent < 0) {
    return 1 / exp(base, -exponent);
  }
  if (exponent > 0) {
    return base * exp(base, exponent - 1)
  }
}

Upvotes: 10

Tieson T.
Tieson T.

Reputation: 21191

Math.pow(base, exponent), for starters.

Example:

Math.pow(12, 2)

Upvotes: 25

Related Questions