Exforsys.com
 
Home Tutorials Microsoft AJAX
 

Microsoft AJAX Library - JavaScript Functions

 

JavaScript Functions

A 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.


 



Read Next: Microsoft AJAX Library - Functions as Variables



 

 

Comments



Post Your Comment:

Members Please Login
Your Name:*
e-mail ID:(required for notification)*
Image Verification: 
 
 Subscribe    

Sponsored Links

 

Subscribe via RSS


Get Daily Updates via Subscribe to Exforsys Free Training via email


Get Latest Free Training Updates delivered directly to your Inbox...

Enter your email address:


 

Subscribe to Exforsys Free Training via RSS
 

 
Partners -  Privacy and Legal Policy -  Site News -  Contact   Sitemap  

Copyright © 2000 - 2009 exforsys.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape