-3
var employeeId = 'abc123';

function foo() {
    employeeId = '123bcd';
    return;

    var employeeId = function(){}
}
foo();
console.log(employeeId);

I am new to javascript programming, could someone explain to me why above output is 'abc123' not '123bcd', I thought the employeeId defined inside foo() should be global variable and overwrite the outside one, am I wrong?

chen.w
  • 129
  • 1
  • 7

1 Answers1

0

When you write:

var employeeId = function(){}

JavaScript actually hoists employeeId and the code becomes this:

function foo() {
    var employeeId;
    employeeId = '123bcd';
    return;

    employeeId = function(){}
}

Since vars declared inside a function have the scope same as of function block, it doesn't overwrite the outer employeeId.

31piy
  • 23,323
  • 6
  • 47
  • 67
  • Thanks for your answer! What if I change 'var employeeId = function(){}' to 'function employeeId(){}', is the result going to be same? – chen.w Mar 27 '18 at 15:49
  • @chen.w -- I recommend you to try it first and observe the behaviour on your own. If you still don't understand, I will be glad to help. – 31piy Mar 27 '18 at 16:04
  • Yeah I just try it on my own it turns out it behaved exact same as function expression, the output is still 'abc123', thank for your help! – chen.w Mar 27 '18 at 16:41