Submodule 5.2: Simple JavaScript file

  • JavaScript in HTML file
  • alert interaction
  • Variables
  • prompt interaction
  • Comments in JavaScript
  • Developer tools (console)

Variables. The "prompt" interaction

What is a variable in JavaScript?

You can imagine variables as boxes.

Variables as boxes
You can create a variable and put something in it.
Just like if you have a box and you put something on it.
You can take that out any time you want and use it. Later you can put something else in the box.

This is exactly what we do with variables. We use variables all the time in JavaScript so soon you will become very familiar with them.
Variables are symbolized with “var” followed by a name of your choice. The name by definition can be anything you want. However, in general, we use names that describe our actions.
Names cannot start with a number and are case sensitive. This means that var name is NOT the same with var Name.


We will use three things, a variable, and two JavaScript methods. 
JavaScript methods are actions that can be performed on objects.  Here we will use the prompt() and the document.write() methods.

  • With the prompt() method a box is displayed were the user writes his input.
  • With the document.write() method we can write something on the document.

So, in this case, we will use prompt() together with document.write() method to welcome a visitor to our page. Notice that we use double quotes "" for text but not for variables.

<!DOCTYPE html>
<html lang="en">
    <title>Example of prompt()</title>
    <h3> Example of prompt()</h3>
       var visitorName;
       visitorName = prompt("What is your name?");
       document.write(" Welcome to my page " +visitorName + "!" );

Copy and paste the code into your editor to see the output. Save the file in the folder ''yourNameWEB2JS" as example05.2.03.html". Next,  open the file (Ctrl+O) in your Chrome. 

For more information: