
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Implementing Math function and return m^n in JavaScript
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
- Related Articles
- Math. fround() function in JavaScript
- Math. hypot() function in JavaScript
- Take two numbers m and n & return two numbers whose sum is n and product m in JavaScript
- Implementing the Array.prototype.lastIndexOf() function in JavaScript
- Implementing custom function like String.prototype.split() function in JavaScript
- Implementing a custom function like Array.prototype.filter() function in JavaScript
- Get minimum number without a Math function JavaScript
- JavaScript Math Object example
- JavaScript outsider function call and return the result
- Implementing binary search in JavaScript to return the index if the searched number exist
- What is math object in JavaScript?
- Implementing Priority Sort in JavaScript
- Implementing Linear Search in JavaScript
- Implementing counting sort in JavaScript
- Implementing block search in JavaScript

Advertisements