- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements
To Continue Learning Please Login
Login with Google