0

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?

Wenfang Du
  • 8,804
  • 9
  • 59
  • 90
  • 3
    The question seems entirely moot as these are both something you should never, ever do. That being said, I would assume the difference is due to order of declaration being handled internally between explicit functions and function expressions. – Rory McCrossan Sep 18 '22 at 14:22
  • @RoryMcCrossan Yes, this is something I'll never do since eslint giving errors, but it's given by an interviewer and I honestly don't know how to explain this. – Wenfang Du Sep 18 '22 at 14:26
  • Understood - that context makes more sense. – Rory McCrossan Sep 18 '22 at 14:29
  • @RoryMcCrossan Not so many people know variable assignments [are not hoisted](https://stackoverflow.com/a/73763526/7881859), I think it's still a worthy question ;). – Wenfang Du Sep 18 '22 at 14:41

1 Answers1

3

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335