Talking to the User: alert, prompt and confirm

Kindergarten, page 8 of 9. A two-minute read.

So far, our programs have only talked to the console, which normal people never look at. (Normal people don't even know it exists. You're in a secret club now.) Let's talk directly to the person using our web page.

Browsers have three built-in ways to pop up a little message box. These only work in the browser, not in Node.js.

alert: show a message

JavaScript
alert("Welcome to my website!");

This pops up a box with your message and an OK button. The page freezes until the user clicks OK.

prompt: ask a question

JavaScript
prompt("What is your name?");

This pops up a box with a question and a text field for the user to type into. Whatever they type comes back to your program. But how do we catch their answer? We need somewhere to store it, which is exactly what you'll learn in Grade 1. Here's a sneak peek:

JavaScript
const name = prompt("What is your name?");
alert("Nice to meet you, " + name + "!");

If you type Mia, the second box will say "Nice to meet you, Mia!" That const name = part means "store the answer in a box labeled name." More on that very soon.

confirm: ask yes or no

JavaScript
confirm("Do you like JavaScript?");

This shows a message with OK and Cancel buttons. Clicking OK gives back true, and clicking Cancel gives back false. (We'll meet true and false properly in Grade 2.)

Note

alert, prompt and confirm are a bit old-fashioned, and real websites rarely use them because they freeze the page and look rather plain. But they're perfect for learning, because they let you build interactive programs before you know how to make proper web pages. Once you reach Grade 11 and 12, you'll learn the modern way to show messages and collect input.

Watch outNot in Node!

If you try alert("Hi") in Node.js, you'll get ReferenceError: alert is not defined. Node doesn't have pop-up boxes because it doesn't have a screen to pop them up on. Use the browser for these!

You did it! Kindergarten is complete. You can write programs, run them in two different ways, and you even know how to leave notes for future-you.

Grab a snack, because next up is Elementary School, where the real building blocks begin. First stop: variables.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning