An explanatin in a complicated function wich uses closures and ojbects

Hello,

I want an explanatin on the following javascript code

var a = (function(y,x) {
   var x = null;
   return {
     foo: function(x) {return this.bar(x*y);},
     bar: function(x){return x + y;}
   }
})(3,4);

console.log(a.foo(2));

Why does this code produces 9?
Thank you

You call a.foo(2), so x inside foo is 2. y is 3, because that is what you pass to the anonymous function. So foo calls this.bar with x*y, which results in this.bar(6). bar just adds x (the parameter you pass to it) and y (still 3), resulting in 6 + 3 = 9.

1 Like

Fine explanation. Than you.