'Recursive Factorial inside Object Javascript
const Calculate = {
factorial(n) {
return n * factorial(n - 1)
}
}
let newNumber = Calculate.factorial(8);
So every time I call the function I get a factorial not defined error. I'm guessing it has something to do with the function being inside an object. Need some help in understanding whats going on. Thank you in advance
Solution 1:[1]
Objects don't create a variable scope, so you need to refer to the object when calling the method.
You can also use this to refer to the object that the method was called on, so you don't have to hard-code the variable name.
const Calculate = {
factorial(n) {
if (n <= 1) {
return 1;
}
return n * this.factorial(n - 1)
}
}
let newNumber = Calculate.factorial(8);
console.log(newNumber);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
