Skip to content

Instantly share code, notes, and snippets.

@SergioR82
Last active November 11, 2018 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SergioR82/66690a0fec0106c7385350a233b75265 to your computer and use it in GitHub Desktop.
Save SergioR82/66690a0fec0106c7385350a233b75265 to your computer and use it in GitHub Desktop.
Recursion - Raise value to power n
function PowExample(val, exp){
//Safe case to catch all possible errors
if(val == 0 || typeof val != 'number'
|| typeof exp != 'number') return 0;
//First base case. Avoid recursivity when
//power is 0.
if(exp === 0) return 1;
//Second base case. return (exp === 1)? val will be executed
//when PowExample has been invocated at least once.
//Recursive Call => val * PowExample(val, exp-1)
return (exp === 1)? val : val * PowExample(val, exp-1);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment