Naming function expression in JavaScript in case of recursive function.

Function expressions in JavaScript is defined as described below:

var recurse = function(){

}

Here recurse is the variable assigned a anonymous function.

Let's see the actual code and it's working.

var recurse = function(str){

if(str.length <= 1){
return str;
}

return recurse(str.substr(1)) + str[0]
}

var recurseRef = recurse
recurse = null
console.log(recurseRef("krishna"))

 

 

Here recurse is  a function expression which recursively reverse a given string. At line # 10 recurse is assigned to a new variable and then after set to null  If you run the above program you will ge an error

TypeError: recurse is not a function

Now let's give a name to the function expression as mentioned below:

var recurse = function recurse(str){

if(str.length <= 1){
return str;
}

return recurse(str.substr(1)) + str[0]
}

var recurseRef = recurse
recurse = null
console.log(recurseRef("krishna"))

 

This will run without any error.

Note: It's always a good practice to give name to function for better error stack trace.