0

I am learning hoisting in JavaScript and practicing some examples.

In an example I am confused of it's output. Here is the example code:

var f = function(){
  console.log("Expression");
}
function f(){
  console.log("Declaration");
}
f();

The output of this code is Expression.
I was expecting the output would be Declaration. If I write the code in this way:

function f(){
  console.log("Declaration");
}
var f = function(){
  console.log("Expression");
}
f();

The output remains same.
How the output of this code is Expression ?

2
  • 3
    Function declarations are processed before any variable assignment (in the same scope of course), no matter where the are located in the source code. Therefore an assignment would always overwrite a declaration with the same name. Commented Jun 1, 2022 at 9:37
  • javascript.info/… Commented Jun 1, 2022 at 9:43

2 Answers 2

0

In JavaScript, function declarations are hoisted, variables are not.

Because of that, in your first example the declaration is hoisted and then overridden.

Same thing happens in your second example.

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

2 Comments

I'd phrase this slightly differently. The key point is that although variable declarations (with var) are hoisted, assignments are not - even if the assignment happens in the same statement as the declaration (as var f = "something";). Whereas with a function declaration, the entire declaration - including the assignment of the function value to the variable - is hoisted. (I realise you almost certainly understand this, I'm just trying to clarify for the OP's benefit.)
@RobinZigmond Absolutely right, and thanks for your additional clarification. :)
0

During initialization, the variable 'f' is assigned the function (Declaration). Initialization happens before code is executed. When the code is executed, the variable 'f' is assigned a new value (Expression) That is, the function declaration will happen before you execute the code, regardless of where in the code the function is declared.

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.