Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the order of execution of code in Javascript?

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.

like image 948
Zeeno Avatar asked Jul 21 '11 13:07

Zeeno


2 Answers

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()

like image 123
Raynos Avatar answered Sep 21 '22 13:09

Raynos


A function declaration is hoisted (so it can be called earlier in the code then it is defined), a function statement isn't.

Does JavaScript execute functions that are defined in a scripting file regardless of whether they're called by an event handler?

A function is called when it is called. Either because something has theFunction followed by () (possibly with arguments) or because it has been made an event handler.

onload="function"

If that is JS, then it will assign a string to something expecting a function. If that is HTML, then you need () to call the function.

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

No. A function is only called when it is called. Declaring a function inside another one just limits its scope.

like image 29
Quentin Avatar answered Sep 22 '22 13:09

Quentin