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 ?

  • 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. – Felix Kling Jun 01 '22 at 09:37
  • https://javascript.info/function-expressions#function-expression-vs-function-declaration – Vladislav Sevostyanov Jun 01 '22 at 09:43

2 Answers2

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.

David
  • 3,552
  • 1
  • 13
  • 24
  • 1
    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.) – Robin Zigmond Jun 01 '22 at 10:08
  • @RobinZigmond Absolutely right, and thanks for your additional clarification. :) – David Jun 01 '22 at 11:42
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.