chopperdave
chopperdave

Reputation: 526

What is the call flow for this window.onload scenario in javascript

index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="Script1.js"></script>
    <script src="Script2.js"></script>
</head>
<body>

</body>
</html>

Script1.js

var Main;
window.onload = Main;

Script2.js

function Main() {
    alert("foo");
}

If I throw a breakpoint @ var Main; and step through the code in WebStorm, it appears to:

  1. Load Script1.js.
  2. Load Script2.js.
  3. Call Main().

However it doesn't execute the statement alert("foo") in that function. Could someone explain what's going on in more detail?

Bonus: In WebStorm, it shows the value of the window.onload field as null and the value of Main as void. What is the difference between a value of null and void?

Upvotes: 0

Views: 630

Answers (2)

Matt Ball
Matt Ball

Reputation: 359966

The contents of Script1.js:

var Main; // declare but do not initialize a variable named "Main"
window.onload = Main; // sets the onload handler to that *undefined* variable

the function named Main is simply never called.


As for the bonus question: What is the point of void operator in JavaScript? and void @ MDC. TL;DR: void is an operator which always returns undefined. Do you understand the difference between null and undefined?

Upvotes: 1

Daniel Doezema
Daniel Doezema

Reputation: 1592

Because Main is an empty variable at that point in script 1. window.onload essentially is set to undefined. window.onload expects a callback function like so...

var Main = function() { my_main_function() }

Upvotes: 1

Related Questions