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?

4
  • 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. Commented Sep 18, 2022 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. Commented Sep 18, 2022 at 14:26
  • Understood - that context makes more sense. Commented Sep 18, 2022 at 14:29
  • @RoryMcCrossan Not so many people know variable assignments are not hoisted, I think it's still a worthy question ;). Commented Sep 18, 2022 at 14:41

1 Answer 1

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.