0

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.

1
  • 3
    Functions are moved to the top, so by the moment console.log#1 runs it's still a function. Then you overwrite it with a string value. Only declarations are hoisted, not the assignments. Commented Jul 9, 2018 at 23:38

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't it technically be var globalString;, function globalString()..., rest of code?
I'm not sure, because it's a function declaration, not a normal hoisted "var". Regardless, whichever it might look like won't have any effect on the resulting script
The results you describe are, of course, correct, but I believe the "interpreted" order of events would be: 1. declare globalString 2. declare func globalString (which overwrites previous undefined var) 3. first IIFE 4. assign string to globalString (overwriting function declaration) 4. second IIFE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.