2

I am no JavaScript expert, but I found some code like this

a();

function a(){
  alert('a');
}

and I was surprised to find it works (I think something like that will not work in Python). I expected that the function a can't be executed before being created. How does interpreter work and why functions can be called before declaration?

Paolo
  • 2,461
  • 5
  • 31
  • 45

3 Answers3

6

This happens because of variable hoisting. See this answer for more info

JavaScript 'hoisting'

Some docs about this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting

If you type it like this, it won't work:

a();
a = function(){
  alert('a');
}
Community
  • 1
  • 1
Willem D'Haeseleer
  • 19,661
  • 9
  • 66
  • 99
1

Code that is within functions and objects will be run whenever that function or object is called. If it is called from code that is directly in the head or body of the page then its place in the execution order is effectively the spot where the function or object is called from the direct code.

See the reference here.

And in our case the function will give the error as you can see the example here.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75
0

It's because function a() is declared via Function Declaration syntax, and Function Declaration are executed right after the script is parsed. With other syntax, Function Expression, like this:

var b = function(){
  alert('b');
}

it won't work (see example).

More info: http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

Ilya Streltsyn
  • 13,076
  • 2
  • 37
  • 57