Getting started

Experience is the best teacher, so let's get started by writing some code. The following code fragment represents the JavaScript version of the timeless Hello World program. Hello World is the typical introduction to a new programming language, and its purpose, surprisingly enough, is to display the words 'Hello World!' on the screen.

<html>
<head>
<title>JavaScript Hello World</title>
<body>
<Script language="JavaScript">
<!-- Start JavaScript

document.writeln("Hello World!");

// end JavaScript -->

</script>
</body>
</html>

To use the JavaScript code above copy the text in any text-editing program, save it as an HTM file, and then open it using a Web browser. For example, create a directory called JavaScript, choose Save As, and then name the file Hello.htm. To view the page, open up your favourite Web browser, choose Open File from the File menu, and then select Hello.htm from the JavaScript folder.

Note that the text file must be saved as ASCII (or plain) text. Some programs, such as Microsoft Word, add formatting information to a file that can cause problems to programs expecting plain text. However, most word processing programs have the ability to save files as text (usually by choosing Save As and then selecting Plain Text or Text File).

Looking at the example, the first interesting point is the <script> tag. The script tag lets the browser know that you are going to be using a scripting language. <script> takes two arguments: the language argument allows you to specify what scripting language to expect (JavaScript in this case), and an optional 'src' tag allows you to place the JavaScript in an external file. If the browser doesn't find the src tag, it assumes that the script is embedded in the HTML.

The <!-- characters ensure that any content between the <!-- tag and --> tags are not displayed in the browser. For JavaScript, this method of enclosing scripts between comment tags guarantees that anyone using a browser that doesn't support JavaScript won't have the source code displayed in the document.

The document.writeln() command performs most of the work in the program. The construction of the statement, two words separated by a dot, is an object-oriented way of instructing the browser to perform an action -- in this example, to write text to the screen.

The remaining code closes the HTML tags and completes the document. Admittedly, this example is a convoluted method of displaying text to the screen, but it does illustrate an important aspect of JavaScript. Using JavaScript you can dynamically generate HTML based upon conditional information. For example, you can use JavaScript to generate browser-specific HTML tags.