You can create recursive functions in a JavaScript object literal in the following ways:
- Using a Named Function Expression;
- Using a Named Function Defined Outside the Object Literal Scope;
- Referring to the Object Method Using
this
.
Using a Named Function Expression
To do recursion and call the current function name inside the function body, you can simply create a named function expression. This makes the name of the function be available only locally, within the function body (scope). For example:
const math = { calcFactorial: function factorial(n) { if (n <= 1) { return 1; } return n * factorial(n - 1); } }; console.log(math.calcFactorial(3)); // 6
Using a Named Function Defined Outside the Object Literal Scope
You could simply define or declare a function outside, and then add the function to relevant object property, for example, like so:
// using function expression const calcFactorial = function(n) { if (n <= 1) { return 1; } return n * calcFactorial(n - 1); }; const math = { calcFactorial, }; console.log(math.calcFactorial(3)); // 6
You can achieve the same using a function declaration, for example, like so:
// using function declaration function calcFactorial(n) { if (n <= 1) { return 1; } return n * calcFactorial(n - 1); }; const math = { calcFactorial, }; console.log(math.calcFactorial(3)); // 6
Referring to the Object Method Using this
"this
" inside the object literal will, by default, refer to the object to which the method belongs to:
const obj = { foo: function() { return this; }, }; console.log(obj.foo() === obj); // true
Please note that this
bounded to the method context could be different depending on how the object method is called. For example, this could be the case if the object method is called using obj.foo.call()
, obj.foo.apply()
or obj.foo.bind()
. Therefore, using this method to do recursion, might not be the best idea.
If you are certain the object method won't be called with an explicitly bounded context, then you can do recursion inside the object method by using this
to refer to the current method on the object, for example, like so:
const math = { calcFactorial: function(n) { if (n <= 1) { return 1; } return n * this.calcFactorial(n - 1); } }; console.log(math.calcFactorial(3)); // 6
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.