Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

circular references among javascript functions

Tags:

javascript

How can one define a pair of functions that call each other in Javascript so that JS-lint does not complain that 'factorial' is being used before it is defined?

function factorial1(n) { return factorial(n); }
function factorial(n) { return n === 0 ? 1 : n * factorial1(n - 1); }

It seems there is no valid ordering that will satisfy JSlint. (One can be embedded in the other, but this would be a nightmare for a collection of functions that all call each other).

Surely this is handled by the language right? Is this just a bug in JSlint? (This question must have been answered somewhere, but I cannot find it!)

like image 608
Dan Oblinger Avatar asked Jun 24 '13 06:06

Dan Oblinger


People also ask

What is circular dependency in JavaScript?

A circular dependency occurs when two classes depend on each other. For example, class A needs class B, and class B also needs class A. Circular dependencies can arise in Nest between modules and between providers. While circular dependencies should be avoided where possible, you can't always do so.

What is circular reference explain with an example?

A circular reference is a type of pop-up or warning displayed by Excel that we are using a circular reference in our formula and the calculation might be incorrect. For example, in cell A1, if we write a formula =A1*2, this is a circular reference as inside the cell A1 we used the cell reference to A1 itself.

What is circular structure in JavaScript?

The circular structure is when you try to reference an object which directly or indirectly references itself. Example: A -> B -> A OR A -> A.

What is circular object array in JavaScript?

An array is called circular if we consider the first element as next of the last element. Circular arrays are used to implement queue (Refer to this and this).


1 Answers

The references inside the functions is not resolved until they are executed. As long as both functions has been defined by the time one of them executes, they will find each other.

If you want to get rid of the JSLint warning, you could define the name of the function, just before:

var factorial;
function factorial1(n) { return factorial(n); }
function factorial(n) { return n === 0 ? 1 : n * factorial1(n - 1); }
like image 174
Markus Jarderot Avatar answered Oct 16 '22 17:10

Markus Jarderot