The Power of Javascript: An Introduction - The Hello World Example
(Page 3 of 4 )
Let's take a look at your first Javascript example, the Hello World example. Write (or copy) the following code into a file with the extension .html as any other Web page you develop.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
<script language="JavaScript" type="text/javascript">
window.alert("Hello World, from the head element");
</script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
window.alert("Hello World, from the body element");
</script>
</body>
</html>
Fire up your IE6 Browser (or any browser you like to use for this example, like Netscape 7.2 or Mozilla Firefox 1.3) and you will get the following message box as the result:

Click on OK and another message box will show up:

And here's the Web page itself. There's no text or any other thing on the page because we didn't include any HTML elements that can be displayed to the page:

Before we discuss your first Javascript example, let's extend it a little bit. Modify your Web page to contain the following code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
<script language="JavaScript" type="text/javascript">
window.alert("Hello World, from the head element");
</script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
window.alert("Hello World, from the body element");
</script>
<h1>
<script language="JavaScript" type="text/javascript">
document.write("Hello Javascript");
</script>
</h1>
</body>
</html>
Reload the Web page and you will get the same two message boxes you saw above, but this time the page will look like this:

As the last change for the Hello World example, modify the code to include HTML comments around the code of the scripts tags (but inside the <script> tags) so it looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Hello World</title>
<script language="JavaScript" type="text/javascript">
<!-- hiding Javascript from old browsers
window.alert("Hello World, from the head element");
// end of the HTML comment -->
</script>
</head>
<body>
<script language="JavaScript" type="text/javascript">
<!-- hiding Javascript from old browsers
window.alert("Hello World, from the body element");
// end of the HTML comment -->
</script>
<h1>
<script language="JavaScript" type="text/javascript">
<!-- hiding Javascript from old browsers
document.write("Hello Javascript");
// end of the HTML comment -->
</script>
</h1>
</body>
</html>
Reload the Web page again and you will get the same message boxes and the same <h1> Hello Javascript element.
Next: Hello World? What's going on? >>
More JavaScript Articles
More By Michael Youssef