0

Since all IIFEs are function expressions, like a function declaration, does JavaScript allocate memory BEFOREHAND(before running any code) for a function expression that is lexically inside the global execution context?

If yes, since functions get stored in memory first before variable declaration, the IIFE's execution context will exit even before the variables are declared because it is called immediately.

(function(){
   console.log(foo);  // (1)
})();
var foo=0;

(1): should return Uncaught ReferenceError: 'a' is not defined Error, but instead of a's value being undefined. Why?

  • 1
    Why should this throw a `ReferenceError`? Variables declared with `var` get hoisted to the "top". – Andreas Sep 21 '20 at 10:56
  • 1
    *"since functions get stored in memory first before variable declaration"* That only applies to function **declarations**. Function *expressions* are evaluated when they are encountered in the source code, just like any other expression. – Felix Kling Sep 21 '20 at 12:42
  • @Andreas **if** IIFEs were allocated in memory (which they are **not** as I know now), according to that above link, the function would be created first & called even before other variables were declared, so any variables accessed inside the iife would be undefined – Pranav Raykar Sep 21 '20 at 14:21
  • As Felix already said, it looks like you're missing the **E** in IIFE. Those are expressions and are therefor not hoisted. – Andreas Sep 21 '20 at 14:38
  • 1
    Partial dupe: [Hoisting order with IIFE involved, specific example](https://stackoverflow.com/questions/53417054/hoisting-order-with-iife-involved-specific-example) – Andreas Sep 21 '20 at 14:39

0 Answers0