Thursday, 24 December 2015

JavaScript difference between var function and function



<script>
  // Through Error
  functionOne();

  var functionOne = function() {
  }
</script>

<script>
  // No error
  functionTwo();

  function functionTwo() {
  }
</script>
The difference is that functionOne is defined at run-time, whereas functionTwo is defined at parse-time for a script block. For example:
Also note that the same is true for variable declarations:
console.log(x); //undefined (not TypeError)
var x = 10;
You can imagine that the JavaScript engine interprets the code like this:
var x; //Declaration is hoisted to top of scope, value is `undefined`
console.log(x);
x = 10; //Assignment happens where you expect it to



No comments:

Post a Comment