Home > Mobile >  Does Var variables get hoisted out of the IIFE?
Does Var variables get hoisted out of the IIFE?

Time:09-28

I have a block of code and I want to exactly know the running order and why the result like this:

   

var variable = 10;
(()=>{
    variable_3 = 35;
    console.log(variable_3);
    var variable_3 = 45;
    variable_2 = 15;
    console.log(variable);
})();

console.log(variable_2);
console.log(variable_3);
var variable=30;

The output for this code is

35, 10, 15, Error

What I understand is:

  1. inside the IIFE we create a global variable_3 and assigned 35.
  2. Then it print out 35.
  3. We create a Var variable_3 inside the IIFE and assigned 45. (Is this Var get hoisted out of the IIFE??)

35.10.15 I understand, can you explain the last number and make my logic correct?

Thanks!

CodePudding user response:

(()=> {
  a = 123;
  console.log(a);  // 123
  console.log(window.a); // undefined
  var a;
})();
(()=>{
  var a = 4;
  (()=>{
    console.log(a);  // undefined
    var a = 5;
  })()
})()
(()=>{
  var source = {};
  (()=>{
    a = source;
    var a;
    console.log(a === source) // true
    // The variable source is indeed assigned to variable a, although variable a is declared after
  })()

})()

var variable is a definition like function , function can use before defined;

main();
function main(){}

so

a = 1;
var a;

like function; use variable before define is also ok;

CodePudding user response:

Both variable_2 and variable_3 were never defined outside of the function, they only exist within it. You would need to define the variables outside of the function to be able to access them, to be logged in this case.

You are also redeclaring variable_3 within the function which then scopes the variable to the IIFE.

A working example:

let
  variable = 10,
  variable_2,
  variable_3;

(()=>{
    variable_3 = 35;
    console.log(variable_3);
    variable_3 = 45;
    variable_2 = 15;
    console.log(variable);
})();

console.log(variable_2);
console.log(variable_3);
variable=30;

  • Related