Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function call wrapped in anonymous function can't be found

Note: This is mostly a theoretical practice.

function one() {
    return [1, function() { one(); }];
}
console.log((one()[1])());

The output gives undefined. Why?

like image 455
chenglou Avatar asked Mar 23 '23 18:03

chenglou


1 Answers

To split it up:

function one() {
    return [1, function() { one(); }];
}
console.log((one()[1])());

one(); // [1, function() { one(); }]
[1] // function() { one(); }
() // undefined

If you return one() it will return the array:

function one() {
    return [1, function() { return one(); }];
}
console.log((one()[1])());

one(); // [1, function() { return one(); }]
[1] // function() { return one(); }
() // [1, function() { return one(); }]
like image 156
Andreas Louv Avatar answered Apr 26 '23 10:04

Andreas Louv