-1

I thought I understood the nature of Immediately Invoked Function Expressions (IIFEs), but now I realise I don't.

I created an IIFE in a piece of code (in a web page using JQuery as it happens). However if I name the function, and try to call that function from the enclosing scope I get an "undefined" error?

The live code behaves differently in IE11 and Firefox 38, which makes things even more confusing. However I created a simple test JSfiddle here-

https://jsfiddle.net/ktqq4uat/

and this is consistent between browsers.

I thought these two lines-

  (function myFunction2() {
   ...

  (myFunction3= function() {
   ...

were pretty much equivalent, but I get an undefined error on "myFunction2" only.

I'd appreciate some help understanding-

1) Why (function myFunction2() {... is hiding the name of the function as well as it's internal scope. What IS the scope of that name?

2) Why myFunction2 and myFunction3 above behave differently.

Rgds

Incans
  • 182
  • 9

1 Answers1

0

Named function expressions only create a variable that:

  • has the same name as the function
  • has a value that is a reference to that function

in their own scope. They also evaluate as a reference to that function so you can pass that reference somewhere (e.g. assign it to myFunction3).

Function declarations create a variable like that in their parent scope. They don't evaluate as anything (because they aren't expressions).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335