1

Why in the first case it will be printed that x is a function and not undefined?

(() => {
    var x

    function x() {}

    console.log(x)
})()

> ƒ x() {}

(() => {
    var x = 1

    function x() {}

    console.log(x)
})()

> 1
z1ne2wo
  • 288
  • 1
  • 6

2 Answers2

2

This just happens because of how JavaScript works with hoisting. Functions with function VARIABLENAME() {} are brought up right under the variable's "existence" calls, and the variable changing values stays in its place, but is relatively moved down because of the function being moved up.

First set

(() => {
    var x

    function x() {}

    console.log(x)
})()

// This gets converted to:
(() => {
    var x // This variable exists

    x = function x() {} // Ya know that variable called x? well its a function

    console.log(x)
})()

2nd set

(() => {
    var x = 1

    function x() {}

    console.log(x)
})()

// This gets converted to:
(() => {
    var x // the variable x exists

    x = function x() {} // Functions are moved to the top, under variable declarations
    
    x = 1 // x is now the value 1

    console.log(x)
})()
Samathingamajig
  • 1,447
  • 1
  • 5
  • 20
1

Hoisting is the behavior of moving the variable (just the left side of the declaration) or function declarations to the top of the corresponding environments during compilation.

The Javascript engine allocates memory for the variables and functions during the creation phase, before the execution of the code happens.

Your first example get interpreted like you wrote it:

// creation phase start
var x = undefined;
function x() {}; // a function is fully hoisted. So x references the function.
// creation phase end

// execution phase start
console.log(x); // therefore x is a function
// execution phase end

Your second example get interpreted a little bit different than you wrote it:

// creation phase start
var x = undefined;
function x() {}
// creation phase end

// execution phase start
x = 1;
console.log(x); // therefore x got overwritten, therefore 1
// execution phase end

One interesting further thing to know: If you write your first example like this ...

var x

(function x() {}) // round brackets

console.log(x)

... the hoisting of the function declaration does not take place, because the first thing the Engine sees, is neither a var nor a function!

wuarmin
  • 1,848
  • 1
  • 11
  • 24