JavaScript/First Program
From Wikibooks, the open-content textbooks collection
Here is a single JavaScript statement, which creates a pop-up dialog saying "Hello World!":
alert("Hello World!");
For the browser to execute the statement, it must be placed inside a <script> element. This element describes which section of the HTML code contains executable code, and will be described in further detail later.
<script type="text/javascript">
alert("Hello World!");
</script>
The <script> element should then be nested inside the <head> element of a HTML document. Assuming the page is viewed in a browser that has JavaScript enabled the browser will execute (carry out) the statement as the page is loading.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Some Page</title>
<script type="text/javascript">
alert("Hello World!");
</script>
</head>
<body>
<p>The content of the web page.</p>
</body>
</html>
This basic hello world program can then be used as a starting point for any new programs that you need to create.
[edit] Exercises
[edit] Exercise 1-1
Copy and paste the basic program in a file, save it on your hard disk as "exercise 1-1.html". You can run it in two ways:
- By going to the file with a file manager, and opening it using a web browser (e.g. in Windows Explorer it is done with a double click)
- By starting your browser, and then open the file from the menu. For Firefox, that would be: Choose File in the menu, then Open File, then select the file.
What happens?
[edit] Exercise 1-2
Save the file above as "exercise 1-2.html". Replace the double quotes in the line alert("Hello World!"); with single quotes, so it reads alert('Hello World!'); and save the result. If you open this file in the browser, what happens?