Last Updated:

Variations on the theme "Hello, world!"

Let's start learning a new programming language with the classic program "Hello, world!", first compiled by the creators of the C language.


Variation One: The Simplest

 

The first step is to create a JavaScript program that inserts the words "Hello, world!" directly into the HTML document. JavaScript programs or scripts are embedded in an HTML document. Take a look at Listing 1.1, which shows the source code of a document with a JavaScript program.

Code Listing 1.1.

<HTML>
  <HEAD>
    <TITLE>Hello, world!</TITLE>
  </HEAD>
  <BODY>
    <H1>JavaScript Test</H1>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
      document.write("Hello, world!");
    // -->
    </SCRIPT>
  </BODY>
</HTML>

As befits any HTML document, it is limited to the <HTML>, </HTML> statements and consists of two sections. The header section is highlighted by the <HEAD> and </HEAD> operators, and the document body section is highlighted by the <BODY> and </BODY> operators.

The JavaScript program in this example is embedded in the body of an HTML document using the <SCRIPT> and </SCRIPT> statement, as shown below: Using the <SCRIPT statement> you can embed JavaScript or VBScript script into your document. The language is specified using the LANGUAGE parameter. The script text is formatted as a comment using the <!-- and --> operators.

 

This is to ensure that the script does not cause problems for users whose browsers cannot work with JavaScript. Such browsers will simply ignore the script. Notice the line that ends the comment:

// --> Two / characters are written before the --> characters. This allows you to ensure that the script works in different browsers. Some of them (for example, Netscape Navigator) in JavaScripts treat the string --> as erroneous.

// characters are used in JavaScript to highlight comments and instruct browsers to ignore the characters written after them (including -->).

The construction /*...*/ can also be used to indicate comments. This method is useful if the comment contains several lines.

<SCRIPT LANGUAGE="JavaScript">
<!--
  document.write("Hello, world!");
// -->
</SCRIPT>

Our first program is quite simple and contains only one line:

document.write("Hello, world!");

Here, for an object named document, the write method is called. As a parameter, the text string "Hello, world!" is passed to it. The string is closed with a semicolon, although this character may not be present. A document object is an HTML document loaded into a browser window. It contains objects, properties, and methods designed to work with the elements of this HTML document, as well as to interact with other objects. The write method writes the welcome string "Hello, world!" to the body of the HTML document. This will make the document look as if this string is in place of the script:

<HTML>
<HEAD>
<TITLE>Hello, world!</TITLE>
</HEAD>
<BODY>
<H1>JavaScript Test</H1>
Hello, world!
</BODY>
</HTML>

 

Variation Two: With Downloadable Source Code

The source code of any script must be included in HTML documents. However, it is technically possible to design JavaScript programs in separate files, and in HTML pages to point to these files with links. The browser, loading HTML documents designed in this way, loads scripts in separate files and substitutes them for the corresponding links. This method of including JavaScript scripts is useful if the same script must be included in many HTML documents, or if there is a need to hide the source code from viewing by users (through the source view).

Files with downloadable scripts are referenced using the SRC parameter of the <SCRIPT tag>, which allows you to specify the URL of the script file. The following example demonstrates the use of the SRC parameter. Listing 1.2 contains the html document source that contains a reference to the hello.js script file.

Code Listing 1.2.

<HTML>
  <HEAD>
    <TITLE>Hello, world!</TITLE>
  </HEAD>
  <BODY>
    <H1>JavaScript Test</H1>
    <SCRIPT LANGUAGE="JavaScript" SRC="hello.js">
    </SCRIPT>
  </BODY>
</HTML>

The link is formatted using the <SCRIPT> and </SCRIPT> operators, but there is not a single line of source code between these statements. This text is wrapped in a hello.js file (Listing 1.3).

Code Listing 1.3. The hello.js file

document.write("<HR>");
document.write("Hello, world!");
document.write("<HR>");

The SRC parameter of the above example specifies only the file name because it is in the same directory as the HTML document file that references it. However, you can specify both a relative path and a full URL, for example: <SCRIPT LANGUAGE="JavaScript" SRC="http://www.myserver.ru/scripts/hello.js"> It is important that the file containing the JavaScript source code is of type js. Otherwise, the script will not work.

 

Variation Three: With Variable and Functions

In JavaScript, functions and variables are actively used. Here's the source code for a simple program that uses a variable and a function (Listing 1.4).

Code Listing 1.4.

<HTML>
  <HEAD>
    <TITLE>Hello, world!</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    var szHelloMsg = "Hello, world!";
    function printHello()
    {
      document.write(szHelloMsg);
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY>
    <H1>JavaScript Test</H1>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    printHello();
    // -->
    </SCRIPT>  
  </BODY>
</HTML>

First of all, notice the document header area highlighted by the <HEAD> and </HEAD> statements. In this area is the definition of the variable and the function, formatted using the operators <SCRIPT> and </SCRIPT>: In addition, in the body of the HTML document there is another section of scripts, highlighted in a similar way: A variable named szHelloMsg is defined using the var operator, and it is immediately assigned the initial value - the text string "Hello, world!".

<SCRIPT LANGUAGE="JavaScript">
<!--
  var szHelloMsg = "Hello, world!";
  function printHello()
  {
    document.write(szHelloMsg);
  }
// -->
</SCRIPT>
<SCRIPT LANGUAGE="JavaScript">
<!--
  printHello();
// -->
</SCRIPT>

JavaScript is not typed. This means that the programmer cannot explicitly specify the type of variables he creates. This type is automatically determined by the JavaScript interpreter when a value is assigned to a variable for the first time. In the future, you can easily change the type of a variable by simply assigning it a value of a different type. The lack of strong typing simplifies scripting, especially for non-professional programmers, but can lead to errors. Therefore, you should carefully monitor what types of data are used. This is facilitated by the use of name prefixes, by which you can judge the type of the variable. For example, you can start text strings with the sz prefix and numeric values with the n prefix.

In addition to the szHelloMsg variable, a function named printHello is defined in the header area of the HTML document using the function keyword. This function is called from a script located in the body of the document and outputs the value of the szHelloMsg variable to the HTML document.

An HTML document and the scripts embedded in it are interpreted as the document is loaded. Therefore, if in the scenario some functions call others or use variables defined in the document, then their definitions (called functions and variables) should be placed above the callers. Placing variable and function definitions in the title section of the document ensures that they are loaded before the document body is loaded.

 

Variation Four: With a Dialog Message Bar

The JavaScript language has built-in tools for displaying simple dialog bars, such as the message bar. Listing 1.6 shows the source code for the JavaScript that calls the alert function to display message dialog boxes.

Code Listing 1.6.

<HTML>
  <HEAD>
    <TITLE>Hello, world!</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    function printHello()
    {
      alert("Hello, world!");      
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY>
    <H1>JavaScript Test</H1>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    printHello();
    // -->
    </SCRIPT>  
  </BODY>
</HTML>

In addition to the dialog box presented in this example, JavaScript scripts can also display more complex scripts. In them, the user can make, for example, a choice of two alternatives or even enter some information.

 

Variation Five: With a Dialog Bar for Entering Information

This example shows how to use the Input Panel dialog box. The text string entered in the dialog bar is displayed in a browser window.

Code Listing 1.7.

<HTML>
  <HEAD>
    <TITLE>Hello, world!</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    function printHello()
    {
      szHelloStr=prompt("Введите приветственное сообщение:", "");
      document.write(szHelloStr);
    }
    // -->
    </SCRIPT>
  </HEAD>
  <BODY>
    <H1>JavaScript Test</H1>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    printHello();
    // -->
    </SCRIPT>  
  </BODY>
</HTML>

The Input Dialog Bar is invoked using the prompt function. The parameters of the function are an introductory message to the user and the initial value of the requested text string (in the example shown, empty).

 

Variation Six: Event Handling

JavaScript has convenient event-handling tools. In the following example, when a user tries to select the "Select me!" link with the mouse cursor over it, a dialog bar appears on the screen with the message "Hello, world!". The source code for the corresponding HTML document with the script embedded in it is shown in Listing 1.7.

Code Listing 1.8.

<HTML>
  <HEAD>
    <TITLE>Hello world!</TITLE>
  </HEAD>
  <BODY>
    <H1>JavaScript Test</H1>
    <A HREF="" onMouseover="alert('Hello, world!');">Select me!</A>
  </BODY>
</HTML>

Here we are interested in the operator string <A>. Recall that this operator is usually used to organize links to other HTML documents or files of various objects. In this case, the reference field of the HREF parameter is empty, but additionally the following construct is included in the <A> statement: It specifies that when the onMouseover (mouse hover) event occurs, the following JavaScript string should be executed: Note that the string is not specified in double quotation marks, but in single quotation marks. In JavaScript, you can use both quotation marks, but the closing quotation mark must be the same as the opening quotation mark. The inner pair of quotation marks should be different from the outer pair.

onMouseover="alert('Hello, world!');"
alert('Hello, world!');

You can install handlers for a variety of events, such as loading a page, clicking a link or form button, selecting a link or form field, and so on.

 

Tasks for self-completion

  1. Modify the last example so that the dialog box does not appear when the mouse cursor is hovered, but when a link is selected (the onClick event).
  2. Modify the example so that when you hover the mouse pointer over the link, you perform a procedure that displays the phrase "Hello, word!" in the browser window.
  3. Write a script that first displays a dialog box, and then, after clicking the "OK" button, writes the phrase "Hello, world!" in the browser window.
  4. Write a script that prompts the user for information and then displays it in a dialog box.
  5. Design the document so that the dialog box for entering information is offered only after the mouse cursor hovers over the link, and the text string entered by the user is displayed as a dialog box, or in a browser window.