Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will using the name of a function inside the same function result in an infinite loop?

Tags:

javascript

Recently, our teacher gave us a quiz on JavaScript. I'm relatively advanced in terms of programming, so when I came upon a question:

Using the name of a function within that same function will result in an infinite loop?

I answered false because of recursion. From my understanding, you have to use the name of a function in order to call it, so recursion would make this not always true.

Am I correct in my understanding, or is the wording different?

like image 875
AniSkywalker Avatar asked Dec 01 '25 02:12

AniSkywalker


2 Answers

This will result in an infinite, recursive "loop" (a stack overflow):

function callMe() {
    callMe();
}

Whereas this will not result in an infinite loop:

function callMe() {
    if (false) {
        callMe();
    }
}

But both snippits are have a function that "uses" the name of that function (to use the wording of your question).

So, the statement:

Using the name of a function within that same function will result in an infinite loop?

really depends on the logic inside the function being invoked (conditional statements, etc).

like image 199
Jonathan.Brink Avatar answered Dec 05 '25 21:12

Jonathan.Brink


It depends on how you are using it.

The statement

Using the name of a function within that same function will result in an infinite loop?

clearly doesn't suggest, How you are using? as in the following example it will not cause infinite loop. The answer should be completely based on the How you are using it?

function callMe() {
    var a = callMe;
}
callMe();
like image 42
Satpal Avatar answered Dec 05 '25 23:12

Satpal