Immediately invoked functions IIFE

var showName = function() {
var name = “hello”;

return function() {
console.log(“return”);
console.log(name)
}
}()
Can i know why above code cannot execute return functions when using parenthesis at the end.

That set of parenthesis is what tells JavaScript to run the showName function, not the function you return inside. If you want to run the returned function too, then you’d need another set of parenthesis.

var showName = function () {
  var name = "hello";

  return function () {
    console.log("return");
    console.log(name);
  };
}()();

Appreciated for your reply, but when i invoke showName() function it does not execute console.log(“inside showName”); it executes only return function, can i know how it works in this context ???

var showName = function() {
console.log(“inside showName”);

var name = “hello”;

return function() {
console.log(“Inside return”);
console.log(name)
}
}()

showName()
// Inside return
// hello

When you’re setting the value of showName, you’re already invoking the function and the function it returns is what becomes showName. You should have already seen “inside showName” printed to the console. Now every call to showName() will just be the output from the function you returned.

Consider the following

var showName = function () {
  console.log("inside showName");

  var name = "hello";

  return function () {
    console.log("Inside return");
    console.log(name);
  };
};

showName();
// inside showName

var showNameReturnFunction = showName();
// inside showName

showNameReturnFunction();
// Inside return
// hello

showName()();
// inside showName
// Inside return
// hello

Thanks a lot, i have completely understood. Appreciated for your prompt response and explanation

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.