Kodeclik Blog

Computing powers in Javascript

Javascript is used by almost every website to do calculations on the browser and support client-side interaction as well as server-side computations. Here we will see how to write simple Javascript programs to compute powers of numbers.
We will embed our Javascript code inside a HTML page like so:
In the above HTML page you see the basic elements of the page like the head element containing the title (“Javascript power demo”) and a body with an empty script tag. The Javascript code goes inside these tags.
There are two ways to compute powers in Javascript. Below is each approach described in detail.

Method 1: Use the exponentiation operator (**)

The first way to compute powers is to use the exponentiation operator (**). Here is some basic code for the same (only the script parts of the page are shown):
When this page is rendered, it will look like:
You can also use the “**=” exponentiation assignment operator like so:
This will also output:

Method 2: Use the Math.pow() function

A second method is to use the Math.pow() function. Here is how that looks (with a newline printed in HTML):
The output is:
In the Math.pow() function, the first argument is the base (2, in our case) and the second argument is the exponent (10, in our case).

Math.pow() when base or exponent is zero

Note that if the base is 0, the result of the exponentiation will be 0. Similarly, if the exponent is 0, the result of the exponentiation will be 1. Here is a simple program to try this:
The output is:

Math.pow() with negative (integer) arguments

You can also use the Math.pow() function with negative (Integer) arguments:
The output is:

Math.pow() with zero raised to negative exponents

If we try a program where zero is raised to negative exponents:
Javascript outputs:

Math.pow() with floating point inputs

Let us try Math.pow() with floating point inputs for either the base or the exponent (or both):
The output will be:
Note that we get a NaN (Not a Number) output whenever the base is negative and the exponent is a floating point number.
Try the same input combinations above with the exponentiation operator and see if you get the same outputs!
Enjoy computing powers in Javascript!
Would you like to learn more Javascript? Checkout our blog post on checking if numbers are within a range in Javascript!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2022. All rights reserved.