Tutorials
Microsoft AJAXA simple fact that was highlighted in the previous chapter, but that is often overlooked, is key to understanding how objects in JavaScript work: code that doesn't belong to a function is executed when it's read by the JavaScript interpreter, while code that belongs to a function is only executed when that function is called.
Take the following JavaScript code that you created in the first exercise of Chapter 2:
// declaring new variables
var date = new Date();
var hour = date.getHours();
// simple conditional content output
if (hour >= 22 || hour <= 5)
document.write("Goodnight, world!");
else
document.write("Hello, world!");
This code resides in a file named JavaScriptDom.js, which is referenced from an HTML fi le (JavaScriptDom.html in the exercise), but it could have been included directly in a < script > tag of the HTML fi le. How it's stored is irrelevant; what does matter is that all that code is executed when it's read by the interpreter. If it was included in a function it would only execute if the function is called explicitly, as is this example:
// call function to display greeting message
ShowHelloWorld();
// "Hello, World" function
function ShowHelloWorld()
{
// declaring new variables
var date = new Date();
var hour = date.getHours();
// simple conditional content output
if (hour >= 22 || hour <= 5)
document.write("Goodnight, world!");
else
document.write("Hello, world!");
}
This code has the same output as the previous version of the code, but it is only because the ShowHelloWorld() function is called that will display "Goodnight, world!" or "Hello, world!" depending on the hour of the day. Without that function call, the JavaScript interpreter would take note of the existence of a function named ShowHelloWorld(), but would not execute it.