JavaScript hoisting for function expression and function declaration

184 views Asked by At

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

There are 2 answers

2
Davi On

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.

0
Vladislav Sevostyanov On

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.