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 ?
()
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With