Skip to content Skip to sidebar Skip to footer

Function Excuted Before Creation

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 P

Solution 1:

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');
}

Solution 2:

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.

Solution 3:

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/

Post a Comment for "Function Excuted Before Creation"