Numbers are used to represent both integer and floating-point values.
Numbers are most commonly expressed in literal forms like 255 or 3.14159 ↴
let num1 = 5; → number
let num2 = 2.5; → number
let num3 = num1 + num2;
console.log(num3); returns ↴
7.5 → number
Exponentiation
Exponentiation is the mathematical process of multiplying a number by itself, raised to the power of another number.
base exponent
base number to multiply.
exponent number of times to multiply the base by itself.
Find the power of a number using recursion
Recursion The act of a function calling itself.
Recursion is used to solve problems that contain smaller sub-problems.
A recursive function can receive two inputs: a base case (ends recursion) or a recursive case (resumes recursion).
Use recursion to find the factorial of 5.
let x = 5;
function factorial(num) {
if (num > 1) { Recursive case
return num * factorial(num - 1);
}
else { Base case
return 1;
};
}
call function
factorial(x); returns ↴
120 factorial of 5 → 120
Math.pow() is equivalent to the exponent operator ** except Math.pow() only accepts numbers.
Initialize a variable to hold the base value.
const num1 = 3; → user input
Initialize a variable to hold the exponent value.
const num2 = 4; → user input
Define a function findPower to find the power of a number.
function findPower(str) {}
The function takes two numbers as input num1, num2 representing the base and exponent and returns the result of raising the base to the power of the exponent.
Recursive case If exponent is negative, calculate the positive exponent
Check if the exponent is negative.
if (exp < 0) {
If true, calculate the positive exponent, return its reciprocal and end execution of function.
return 1 / findPower(base, -exp)
Base case
Check if the exponent is 0
if (exp === 0) {
If true, return 1 (base case), and end execution of function.
return 1
Base case
If the exponent is 1 return the base (base case), and end execution of function.
if (exp === 1) return base
Recursive case
Multiply the base by the result of the function with exponent decreased by 1
return base * findPower(base, exp - 1)
Call the function with ↴
findPower(num1, num2);
Find 3 to the power of 4 → 34
const num1 = 3;
const num2 = 4;
function findPower(base, exp) {
if (exp < 0) {
return 1 / findPower(base, -exp);
}
if (exp === 0) {
return 1;
}
if (exp === 1) return base;
return base * findPower(base, exp - 1);
}
call function
findPower(num1, num2); returns ↴
81