To find the Power of a number in JavaScript you can use the readily available function Math.pow().
But sometimes, especially in the interviews they might ask you to write a simple JavaScript program to calculate the power of a number without using the JavaScript pow() function.
Here is a small example of “Power of a number”
52 = 5 * 5, value is 25
Here in the above expression example, 5 is the base & 2 is the exponent
Another example, 53 = 5 * 5 * 5, value is 125
So basically we need get two values from the user, base & exponent then to find the power, just loop exponent times and multiple the base value.
Let’s write a custom JavaScript function to find the power of a number:
function PowerOfNumber(b,e){
var i, pow = 1;
//loop exponent times
for(i=0; i<e; i++){
//multiple the base value
pow = pow*b;
}
return pow;
}b and e is the base and exponent in the above function
Let’s write a HTML example to see the output:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Javascript to find power of a number</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Load Bootstrap library for better UI look & feel -->
<link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
/>
<script>
function calcPower() {
//get the value of base & power
var b = document.getElementById("pow").value;
var e = document.getElementById("exp").value;
var res;
res = PowerOfNumber(b,e);
document.getElementById("res").innerHTML = res;
}
function PowerOfNumber(b,e){
var i, pow = 1;
//loop exponent times
for(i=0; i<e; i++){
//multiple the base value
pow = pow*b;
}
return pow;
}
</script>
</head>
<body>
<div class="container">
<br />
<h2>Javascript to find Power of a number without using pow()</h2>
<br />
<div class="row">
<div class="col-lg-4">
<div class="input-group mb-4">
<input type="number" class="form-control" id="pow" placeholder="Base" min="1">
<div class="input-group-prepend">
<span class="input-group-text">-</span>
</div>
<input type="number" class="form-control" id="exp" placeholder="Exponent" min="1">
<button type="submit" class="btn btn-primary" onclick="calcPower()">Submit</button>
</div>
<div>Result: <span id="res"></span>
<div>
</div>
</div>
</div>
</div>
</body>
</html>See the demo of this above script here:
