What is the order of execution of code in Javascript?

Zeeno picture Zeeno · Jul 21, 2011 · Viewed 13.5k times · Source

How exactly is code in JavaScript executed? I mean in what order? Would there be a difference in the order of execution if I declared a function like this:

function render() {
    // Code here
}

instead of this:

var render = new function(){
    // Same code here
}    

Does JavaScript execute functions that are defined in a scripting file regardless of whether they're called by an event handler? (e.g. onload=function()).

And finally if a function is defined in another function, when the parent function is called, is the lower function also called too? e.g.

function a(){

    function b(){
        // code
    }

    function c(){
        //code
    }

}

I'm trying to get a concrete understanding of order of execution in JavaScript.

Answer

Raynos picture Raynos · Jul 21, 2011
var render = new function(){
  // same code here
}

The new keyword doesn't create a new Function. It creates a new object by running the function. So this would actually run the body of the method and return an object instead.

If your asking when are functions parsed and added to scope then that's implementation specific, but all functions are hoisted to the top of scope and generally parsed before any code is executed.

Functions are only executed when you call them by invoking f()