JavaScript OOP Tutorial: JavaScript Closures

This is a JavaScript DOM exercise from Chapter 3 of Microsoft AJAX Library Essentials: JavaScript in ASP.NET AJAX 1.0 Explained.

JavaScript functions implement the concept of closures, which are functions that are defined inside other functions, and use contextual data from the parent functions to execute. Find a complete and technically accurate definition of closures at

In JavaScript a function can be regarded as a named block of code that you can execute, but it can also be used as a data member inside another function. With other words, a JavaScript function can contain other functions.

Say that we want to upgrade the initial ShowHelloWorld() function by separating the code that displays the greeting message into a separate function inside ShowHelloWorld(). This is a possible implementation, and the output continues to be the same as before:

// call function to display greeting message

// "Hello, World" function
function ShowHelloWorld()
  // declaring new variables
  var date = new Date();
  var hour = date.getHours();

  // call DisplayGreeting 

  // display greeting
  function DisplayGreeting()
    if (hour >= 22 || hour <= 5) 
      document.write("Goodnight, world!");
      document.write("Hello, world!");

Here, we created a function named DisplayGreeting() inside ShowHelloWorld(), which displays a greeting message depending on the hour parameter it receives. The execution rules apply here as well. This new function needs to be called explicitly from its parent function in order to execute.

Implement the exercise step by step and find detailed explanations in our book, Microsoft AJAX Library Essentials: JavaScript in ASP.NET AJAX 1.0 Explained.