1

had a question about functions. Suppose I have a function statement as shown below:

function someFunction() {
}

This gets assigned to global 'window' object as shown below:

someFunction: ƒ someFunction()

But if there is an IIFE as shown below, how is it attached to global object?

 (function() {
    console.log('I am an IIFE');
 }());

I created such function, then tried seacrhing 'window' object but didn't find anything.

Uzair Khan
  • 2,812
  • 7
  • 30
  • 48
  • 6
    It is not attached to the global object. It's a function *expression*, not a function declaration. They both result in a function being available in some context. In the IIFE case the context is that expression only. – Pointy Jan 24 '20 at 13:54
  • 2
    It's also anonymous by nature, there is no name to store it under in the window object. – Luca Kiebel Jan 24 '20 at 13:56
  • 2
    You didn't give it any name. What did you expect it to show up as? (Note that giving IIFEs names doesn't help either, but that's a separate topic…) – deceze Jan 24 '20 at 13:57
  • var xyz = function() { console.log('Test me'); } This being a function expression gets attached to global object, the only difference between this and IIFE is that the invocation to IIFE is immediate and for above shown function can be called from elsewhere. Can you explain? – Uzair Khan Jan 24 '20 at 13:57
  • 2
    It's the difference between the statement `5;` and the statement `var x = 5;` – Pointy Jan 24 '20 at 13:58
  • So, if anonymous, the function is not attached else it does? Regardless of what type it is, function statement/declaration. Correct? – Uzair Khan Jan 24 '20 at 14:01
  • 1
    If *expression*, the function is not attached. Unless you explicitly attach the function with `var x = function () {}`. – deceze Jan 24 '20 at 14:02
  • Thanks all, I am clear now. – Uzair Khan Jan 24 '20 at 14:03
  • 2
    Note that you cannot have an anonymous function *statement*… – deceze Jan 24 '20 at 14:05

0 Answers0