A Javascript quiz about hoisting

Viewed 34
var d = 1;

(function(){
  d = '2'
  console.log(typeof d)
  function d() {
  }
})()

console.log(typeof d)

Could you explain why the second log prints out "number"?

var d = 1;

(function(){
  d = '2'
  console.log(typeof d)
})()

console.log(typeof d)

I tried to remove the function from the IIFE, and the result of second log becomes "string". I am very confused about it.

1 Answers

The first code:

var d = 1;

(function(){
  d = '2'
  function d() {
  }
})()

because of function hoisting (function definitions are hoisted to the top of the containing scope - I think I worded that right), it's identical to

var d = 1;

(function(){
  function d() {
  }
  d = '2'
})()

Now, d inside the IIFE is declared locally, so the "global" d is irrelevant and untouched by d='2'

Related