Skip to content

Input and Output

Getting Input

  • We're going to start with a simple way to get input from our users with the prompt() dialog box.
  • prompt() is a method of the window object.
    // Using a prompt

    let lastName;

    lastName = prompt("Enter your last name -- This is what the user sees");

How it works

  • When JavaScript sees this prompt("...") it will open a dialog box.
  • The text inside the quotes will be displayed in the dialog box for the user to read.
  • When the user enters something in the text box and presses the OK button, the data entered is put into the variable to the left of the prompt().
  • We can then use the variable with its new content.


  1. Demo: prompt() unit01/demos/demo-prompt.html

Displaying Output

Here's a piece of JavaScript that you've seen already using document.write(). We'll explain it in more detail now.

    // Our first way to display output

    document.write("This is a string");

How it works

  • The word document refers to the HTML page that contains this JavaScript program.  Note: document is an object, one of the most famous objects in the JavaScript language.
  • The period (.), called the dot, is a way to access things inside of your document.
  • The word write is, in object oriented talk, a method of the document object, although some authors refer to it as the write "function," which is also fine. Don't worry if this doesn't make complete sense yet--it will in time.
  • Next is a set of parentheses with some quoted words inside.
  • And, finally, a semicolon!
  • What happens when this is run by JavaScript?
  • When this method is run it takes whatever is in the parentheses and outputs it to the HTML page right where the "write" happens to be. In our labs that will be just after the <script> tag ends.
  • What can I put in a "write"?
  • Everything that we are creating in our programs can go in a write--it's handy.

Hands on work


  1. Demo: document.write() unit01/demos/demos/demo-output.html


  1. Lab04: Using variables in JavaScript
    • unit01/labs/lab-04-variables.html


  1. Lab04 exercise
    • unit01/exercises/exercise-04.html