Search code examples
javascripthoisting

javascript hoisting for global variable and function


I was wondering about hoisting. I know if global function name same with global variable, function overwrite variable's name. Is it right?

here is my code.

(function() {
  console.log('console.log#1 ' + globalString); // globalString function 

})();

var globalString = 'I\'m globalString variable';

(function() {
  console.log('console.log#2 ' + globalString); // string
})();

function globalString() {
  console.log('I\'m globalString function');
}

It's result show me like blow

console.log#1 function globalString ()
{
    console.log ( 'I\'m globalString function' );
}

console.log#2 I'm globalString variable

If function definition overwrite variable's console.log#2 print globalString function. I don't know how variable and function hoist. please help.


Solution

  • Function declarations (like your globalString()) are hoisted. To the interpreter, your code looks something like this:

    var globalString = function globalString() {
      console.log('I\'m globalString function');
    };
    
    (function() {
      console.log('console.log#1 ' + globalString); // globalString function 
    })();
    
    globalString = 'I\'m globalString variable';
    
    (function() {
      console.log('console.log#2 ' + globalString); // string
    })();

    Before the initial IIFE runs, globalString is the function. After the initial IIFE runs, but before the second IIFE runs, globalString is then reassigned to the string. Ordinary assignments aren't hoisted - only the variable name is.