Variable Hoisting and expressions

28 September 2015

When javascript runs it first parses the entire file for variable and function declarations. This is a process called hoisting. Say you have learned about this and think you understand how it works. You write the following script and it fails

function demo(){
  hoisted1()
  hoisted2()
}
demo()

function hoisted1(){
  console.log('hoisted1 executed')
}

var hoisted2 = function(){
  console.log('hoisted2 executed')
}

A common pitfall is when you know about hoisting but expect an expression to also be hoisted. See hoisted1 is a function declaration and gets hoisted. hoisted2 is a variable declaration and gets hoisted but the expression does not. Futher, hoisted2โ€™s expression value is not computed and made available until after itโ€™s original place in the script.

If you need help solving your business problems with software read how to hire me.



comments powered by Disqus