javascriptfunctionvarvariable-declarationhoisting

Different behaviors between the same var name and function name VS two same function name


Recently, I received this interview question, I know it's weird to declare var name and function name the same, but the code runs without errors, and I don't know how to explain this behavior, hence the question.


In the Chrome console, the following code logs 1:

var foo = function () {
  console.log(1)
}
function foo() {
  console.log(2)
}
foo()

And the following code logs 2:

function foo() {
  console.log(1)
}
function foo() {
  console.log(2)
}
foo()

Why are the results not the same?


Solution

  • Function declarations, including the assignment of their values, are hoisted. Variable assignments are not.

    In the first case, the function declaration for foo is hoisted so is overwritten by the variable assignment even though that appears earlier in the source order.