Tuesday 16 July 2019

Javascript variable function declaration vs expression

The main practical difference is hoisting. For example:
foo(); // alerts 'hello'
function foo() {alert('hello');}
vs
foo(); // throws an error since foo is undefined
var foo = function() {alert('hello');}
Also, this is undefined behavior
function foo(){
  if (true) {
    function bar(){}
  }
  bar();
}
while this is ok.
function foo(){
  if (true) {
    var bar = function(){}
  }
  bar();
}

https://softwareengineering.stackexchange.com/questions/160732/function-declaration-as-var-instead-of-function

No comments:

Post a Comment