Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between window.onload = function(){ .. } / window.onload = function(){ .. }();

Tags:

javascript

I'm using in a project the following code which is not working:

window.onload=function(){
 //code here
};

but if I add at the end () it works:

window.onload=function(){
 //code here
}();

My question is, what's the difference? What does the () at the end?

I presume that the first one doesn't work because somewhere else the "onload" has been already called killing this one.

Would it have the same behaviour if I always use the second option ?

like image 521
themazz Avatar asked Oct 31 '13 14:10

themazz


2 Answers

() at the end of function, calls this function immediately after declaration

window.onload=function(){
 //code ehere
}() // function is called 

And in this case

window.onload=function(){
 //code here
}; 

function will be called after

window.onload()
like image 122
Ilya Avatar answered Oct 08 '22 16:10

Ilya


When you have () after a lambda function such as that, it means you're calling the function immediately on that line.

So, for example,

var x=function() {
    return 5;
}();
console.log(x);

would log 5 in the console. In the case of

window.onload=function() {
    //code here
}();

that function most likely returns another function that gets called when the page loads.

For example,

window.onload=function() {
    return function() {
        console.log("Hello!");
    };
}();

will log "Hello!" in the console when the page loads.

like image 22
TND Avatar answered Oct 08 '22 15:10

TND