We are required to write a JavaScript function that takes in two numbers say m and n. Then function should calculate and return m^n.
For example − For m = 4, n = 3, then
power(4, 3) = 4^3 = 4 * 4 * 4 = 64 power(6, 3) = 216
The code for this will be the following using the power() function in JavaScript −
Example
const power = (m, n) => { if(n < 0 && m !== 0){ return power(1/m, n*-1); }; if(n === 0){ return 1; } if(n === 1){ return m; }; if (n % 2 === 0){ const res = power(m, n / 2); return res * res; }else{ return power(m, n - 1) * m; }; }; console.log(power(4, 3)); console.log(power(6, 3));
Output
And the output in the console will be −
64 216