Search code examples
javascriptclosures

JavaScript closure not showing parameters properly


I was playing a bit with closures in order to learn them, and made this code:

function showName(a,b,c){
  (function nombresAnidados(a){
  (function(b){
    (function(c){
      console.log("hola " + a + " " + b + " " + c);
    })(a)
  })(b)
})(c)
}

showName("cat","dog","horse");

I was expecting it to print out: "Hi, cat dog horse" but instead it prints: "Hi, horse dog horse"

Please, run it here:

    function showName(a,b,c){
      (function nombresAnidados(a){
      (function(b){
        (function(c){
          console.log("Hi, " + a + " " + b + " " + c);
        })(a)
      })(b)
    })(c)
    }
    
    showName("cat","dog","horse");

What causes this behavior?


Solution

  • try :

    function showName(a, b, c)
      {
      (function nombresAnidados(x)  // here your arg a get the value of c
        {
        (function (y)
          {
          (function (z)
            {
            console.log(  `hi : ${x} - ${y} - ${z}` );
            })(a) // --> z   (cat)
          })(b)  // --> y   (dog)
        })(c)   // --> x   (horse)
      }
    
    showName("cat", "dog", "horse");

    note: your code is not really a closure ;)