JavaScript/First program

From Wikibooks, open books for an open world
Jump to navigation Jump to search

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 HTML <script> element. This element describes which part of the HTML code contains executable code. It will be described in further detail later.

  alert("Hello World!");

The <script> element should then be nested inside the <head> element of an 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>
<html lang="en">
    <title>Some Page</title>
      alert("Hello World!");
    <p>The content of the web page.</p>

This basic 'Hello World' program can then be used as a starting point for any new program that you need to create.

Exercises[edit | edit source]

1. Copy and paste the basic program into a file, and save it on your hard disk as 'exercise_1-1.html'. You can run it in different ways:

  • By going to the file with a file manager and opening it using a web browser.
  • By starting your browser and then opening the file from the menu.
  • By starting your browser and then specify the URL to 'exercise_1-1.html' with the file protocol. Please note that a) there are 3 slashes after 'file:' and b) replace 'temp' with the name of your directory.
    • Windows: file:///C:/temp/exercise_1-1.html (it's Windows syntax, nevertheless use slash instead of backslash)
    • Linux: file:///temp/exercise_1-1.html

What happens?

Click to see solution
A dialog appears with the text: Hello World!

2. Save the above file 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?

Click to see solution
Nothing changes. A dialog appears with the text: Hello World! Double quotes and single quotes (apostrophes) are equivalents in JS.