0
votes

Someone sent me this pic on Discord saying Functions are hoisted first and then the variables.

prnt .sc/xdwc9a (please delete the space before dot, I dont want to spam)

His statement seems true cause the function is being invoked without throwing any error.

Kyle Simpson also says the same thing in his YDKJS book:

  • bit .ly/39Wolka

However, when i experiment with it, I dont get what I expect. logger() // 10

function logger(){

var x = 10;

function x(){

console.log('Function code')

}

function x(){
  console.log("more code")
}

console.log(x)

}

This returns 10 however since functions are hoisted first, x function should have been hoisted and in the second run of hoisting (which hoist variables) when it tried to hoist var x; it should've ignored it cus the function x was already hoisted but it doesn't seem like that's what happening here!

Am I missing something?

2

2 Answers

0
votes

Using the mental picture of hoisting, I'd think about it like this.

Note that if an identifier a is used for a function, a subsequent re-declaration var a makes no difference. a still references that same function.

function a(){console.log('hello')}
console.log(typeof a);     //function
var a;
console.log(typeof a);     //function
a();                       //hello

Also, if an identifier a is used for a function, that identifier can be reassigned to say a number.

'use strict';
function a(){}
console.log(typeof a);     //function
a = 123;
console.log(typeof a);     //number

Even in strict mode, the declaration of a function seems to then allow the use of that identifier with no preceding var or let.

Taking your logger code, and moving the nested functions and var x to the top, as per the model of hoisting

function logger(){
  function x(){                     //hoisted at compile time
    console.log('Function code')
  }
  function x(){                     //hoisted at compile time
    console.log("more code")
  }
  var x;                            //hoisted at compile time
  //execution time code
  x = 10;
  console.log(x)
}

logger();

At the console.log(x) line, x is the number 10.

0
votes

Variables get hoisted at first as well as functions. But when variables are hoisted first, their values are undefined. On the other hand, function declarations (not expressions or IIFE) get hoisted with their content.

Here is hoisting from MDN.