0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Math.pow in JavaScript: Syntax and Examples

Use Math.pow(base, exponent) in JavaScript to calculate the power of a number, where base is the number to be raised and exponent is the power. It returns the result of base raised to the exponent.
📐

Syntax

The syntax of Math.pow is simple and takes two arguments:

  • base: The number you want to raise to a power.
  • exponent: The power to which the base is raised.

The function returns the value of base raised to the power of exponent.

javascript
Math.pow(base, exponent);
💻

Example

This example shows how to calculate 2 raised to the power of 3 using Math.pow. It prints the result to the console.

javascript
const base = 2;
const exponent = 3;
const result = Math.pow(base, exponent);
console.log(result);
Output
8
⚠️

Common Pitfalls

Common mistakes include:

  • Passing non-numeric values, which results in NaN.
  • Using negative exponents without understanding it returns fractional results.
  • Confusing Math.pow with the exponentiation operator ** (which is newer and often preferred).

Always ensure both arguments are numbers to avoid unexpected results.

javascript
/* Passing strings that can be converted to numbers */
console.log(Math.pow('2', '3')); // Works but converts strings to numbers

/* Passing non-numeric strings */
console.log(Math.pow('two', 3)); // NaN

/* Using numbers */
console.log(Math.pow(2, 3)); // 8
Output
8 NaN 8
📊

Quick Reference

UsageDescription
Math.pow(base, exponent)Returns base raised to the exponent power
Math.pow(5, 2)Returns 25 (5 squared)
Math.pow(4, 0.5)Returns 2 (square root of 4)
Math.pow(2, -1)Returns 0.5 (reciprocal of 2)

Key Takeaways

Use Math.pow(base, exponent) to calculate powers in JavaScript.
Both base and exponent should be numbers to avoid NaN results.
Negative exponents return fractional values (reciprocals).
The exponentiation operator ** is a modern alternative to Math.pow.
Math.pow can handle fractional exponents for roots.