Introduction To Javascript
Getting Started

Hello World

The first step for many programmers is to get the programming language to provide on-screen output. This is very straightforward in Javascript.

Study the following example

<html>
<head>
<title>Hello World</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>

Notice that all Javascript statements must be contained within the script tags. The document.write command writes HTML to the page. HTML tags can be included within the quotation marks.

Exercise 1

Copy the code into Notepad and save your file with the extension .htm changing the file type to All Files in the FileSaveAs dialog box. Load the page in your browser and your first piece of Javascript is written.

Where do I place the script tag?

The script tag can be placed in the head or the body section of the HTML page. The order in which the browser renders the page is changed when you do this. The browser renders the code in sequence. In the above example the script tag appears in the body of the document and the text is displayed as the browser arrives at that section. Try adding a line of HTML above and below the script to see exactly where the output appears. Next try copying the whole script into the head section of the document. You will see that it runs the Javascript before the page has loaded. All other content appears after the script has run.

As a basic rule of thumb you should place the script tag where you want it to be run. If you are using Javascript to produce text on the page as the document is loaded then place the script tag in the body of the document at the point at which you want the code to be run. Many of the scripts found later in this guide are not designed to run as the document loads and so appear in the head section of the document.