Avoid null ref in recursive call

I have a recursive call and I want to be safe (in case my func is null which will throw an error), currently I am using a function call inside the function itself, which may have some ref problem in case of null, there is a way to do is this call safe in JS?



function myFunc(){


I tried searching on the internet for some ways to overcome this but couldn't find ...


source to share

2 answers

In this case, I would use .callee arguments as shown below

function myFunc(){


This gives you a reference to the function and you don't need to use the function name.

Let me know if this solves your problem.

Update. Since Pr0gr4mm3r is mentioned in the comment below, this is not available in ECMAScript 5 Strict Mode Good luck!



You can verify that you have a link to myFunc

using a closure:

var myFunc = (function() {
    function myFunc() {
    return myFunc;

// demo
var tmp = myFunc;
myFunc = null;
tmp(); // infinite recursion


If you don't need to support IE8 and below, a named function expression is better and does the job:

var myFunc = function myFunc() {


Unfortunately IE8 has a bug that prevents this from working (see Named Function Expressions demystified by Yuri "kangax" Zaitsev and Double-take blog post ).



All Articles