Reputation: 2721
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.
Upvotes: 6
Views: 15678
Reputation: 944216
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.
Upvotes: 4
Reputation: 1388
When you declare a function, it is not executed until it's called (that's true for ones declared in onload and other events as well).
For nested functions, they are not executed automatically when the top-level function is called UNTIL the containing function calls them.
Upvotes: 0
Reputation: 169511
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()
Upvotes: 4