0

I have this self execute function that call itself:

(function a(x){
    if(x > 0){
        x--;
        console.log(x);
    }
    a(x);
})(5);
//outputs 4 3 2 1 0

This is correct behaviour . But if i pass this function to a variable how i can achieve the same behaviour?

var a = (function (x){
    if(x > 0){
        x--;
        console.log(x);
    }
    //a(x); outputs error
})(5);
user2019037
  • 764
  • 1
  • 7
  • 14

1 Answers1

4

In the second case, the result of your Immediately Invoked Function Expression (IIFE), which will be undefined, is assigned to the variable a. Thus, a does not have a function associated with it.

James Sumners
  • 14,485
  • 10
  • 59
  • 77