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.
1
2
3
4
5
    // 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.
  • Technically, when you call prompt(), you're actually calling window.prompt(). prompt() is a method of the window object, which is the object that represents the browser window. In this case, we can leave off the window. part and just use prompt(). This is because the window object is the default object for JavaScript in a web browser.

Demo

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

Displaying Output

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

1
2
3
    // Our first way to display output

    mcPrint("This is a string");

How it works

  • The word mcPrint refers to the function that is provided to you automatically in this class.
  • A function behaves like a method in that it is a piece of code that can be run when called. The difference is that a function is not part of an object.
  • We use mcPrint() to display output to the user in the first four units of this class. In Unit 5, we'll use a more standard way to display output.
  • If a friend is helping you with your code, they might not be aware of mcPrint() and give you advice that is accurate for the standard way of displaying output, but not units 1-4 of this class.
  • 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 function is run it takes whatever is in the parentheses and displays it on the web page.
  • What can I put in an mcPrint()?
  • Everything that we are creating in our programs can be displayed with mcPrint()--it's handy.

Hands on work

Demo

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

Labs

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

Exercises

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