0

When I run the following piece of JS code:

var x = (function () {
    console.log('Hello x!');
});

var y = function () {
    console.log('Hello y!');
};

var z = (function () {
    console.log('Hello z!')
    return 2;
})();

x();

y();

The following output is printed on the browser's console:

Hello z!

Hello x!

Hello y!

Why "Hello z!" is printed before "Hello x!" & "Hello y!". And how does the Immediately Invoked Function Expression (IIFE) interact with the 'z' variable?

P.S. : I am a beginner.

  • 2
    The word "immediately" means "now" or "right away". By adding the `()` to the end of the function expression, the function is immediately *called* (invoked) and the return value is the value of `z`. – Pointy Jan 09 '20 at 16:57
  • 2
    The IIFE is immediatly invoked (called/run/etc). Before both X and Y. – evolutionxbox Jan 09 '20 at 16:57
  • Possible duplicate of [What is the (function() { } )() construct in JavaScript?](https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – Nick is tired Jan 09 '20 at 17:00

3 Answers3

1

Because this is IIFE:

var z = (function () {
    console.log('Hello z!')
    return 2;
})();

Without IIFE above code could be rewritten as:

var x = (function () {
    console.log('Hello x!');
});

var y = function () {
    console.log('Hello y!');
};

var z = function () {
    console.log('Hello z!')
    return 2;
};
z();

x();

y();

That's why 'Hello z' is printed first

bapafes482
  • 444
  • 4
  • 18
  • OP knows that this is a IIFE (_"And how does the Immediately Invoked Function Expression (IIFE) interact with the 'z' variable?"_) – Andreas Jan 09 '20 at 17:01
  • "could be rewritten" yes and no. In this example `z` is a function. In the original `z` is `2`. – evolutionxbox Jan 09 '20 at 17:02
  • 1
    `var z = (function() { return 2; })()` is not the same as `var z = function() { ... }; z();` – Andreas Jan 09 '20 at 17:02
  • @evolutionxbox @Andreas better luck rewriting above code so it stays the same (oops!) to illustrate why `Why "Hello z!" is printed first. – bapafes482 Jan 09 '20 at 17:13
0

Like the above answer it's how the your code is written, the call stack is calling the IIFE first, then the x function, then the y function. If you want a good visual representation, check out Loupe by Philip Roberts(http://latentflip.com/loupe/). It lets you write code and step through how it's called and executed. Helped me a lot when trying to understand execution sequence.

0

The first I in IIFE means Immediately.
That's why this function is executed first.

In addition, the IIFE can not interact with the 'z' variable.
But you can pass arguments to it like this :

var hi = 'Hello z!';

var z = (function (txt) {
    console.log(txt)
})(hi);

Hope this would help.

alexronsaut
  • 140
  • 7