Chapter 5: JavaScript Basics - Episode 5
User Input with prompt()
Understanding prompt() in JavaScript
The prompt() method in JavaScript is one of the simplest ways to get input from a user. It displays a dialog box that prompts the user for input, with an optional message to display to the user.
let userName = prompt("What is your name?"); console.log("Hello, " + userName + "!"); // You can also provide a default value let favoriteColor = prompt("What is your favorite color?", "blue"); console.log("Your favorite color is " + favoriteColor);
How prompt() Works:
Syntax
prompt(message, defaultValue)
- message: Text to display to the user (required)
- defaultValue: Default input value (optional)
Return Value
- String: The text entered by the user
- null: If the user clicks "Cancel"
- Empty string: If the user doesn't enter anything and clicks "OK"
Important Notes About prompt():
Limitations & Warnings
- prompt() is blocking - it pauses code execution until the user responds
- Return value is always a string (or null) - you'll need to convert to numbers if needed
- No input validation - users can enter anything or nothing
- Not suitable for passwords (as our characters discovered) - text is visible
- Many modern browsers allow users to prevent sites from creating dialogs
- Rarely used in production applications - better UI options exist
Despite these limitations, prompt() is perfect for learning JavaScript because it's simple and doesn't require HTML forms or DOM manipulation to get user input.
When To Use prompt()
- Learning JavaScript fundamentals
- Quick prototyping and testing
- Simple applications where UI isn't critical
- Educational examples like our Mad Libs game!
Converting Strings to Numbers
Since prompt() always returns a string, you need to convert the input if you want to work with numbers:
// Without conversion let num1 = prompt("Enter first number:"); let num2 = prompt("Enter second number:"); console.log(num1 + num2); // If user enters 5 and 10, result is "510" (string concatenation) // With conversion let num1 = Number(prompt("Enter first number:")); let num2 = Number(prompt("Enter second number:")); console.log(num1 + num2); // If user enters 5 and 10, result is 15 (numeric addition)
Ways to Convert Strings to Numbers
Using Number():
let num = Number("42"); // 42
Using parseInt():
let num = parseInt("42"); // 42
Using unary plus operator:
let num = +"42"; // 42
Using parseFloat() for decimals:
let num = parseFloat("42.5"); // 42.5
Activity: Mad Libs Word Game
Now let's learn how to use prompt() by building a Mad Libs game! Mad Libs is a word game where players fill in blanks with different types of words (nouns, verbs, adjectives, etc.) to create a funny story.
// Mad Libs: "The Adventure" function playMadLibs() { // Get words from user let adjective1 = prompt("Enter an adjective:"); let noun1 = prompt("Enter a noun:"); let verb1 = prompt("Enter a verb ending in 'ing':"); let adverb1 = prompt("Enter an adverb:"); // Check if user canceled if(adjective1 === null || noun1 === null || verb1 === null || adverb1 === null) { return "Game canceled!"; } // Create the story let story = `Once upon a time, a ${adjective1} programmer was ${verb1} ${adverb1} on their computer. Suddenly, a wild ${noun1} appeared on the screen!`; // Display the completed story return story; }
Try It Yourself: Space Adventure Mad Libs
Click the button below to play a Mad Libs game using prompt(). You'll be asked to provide different words to complete a space adventure story!
Your completed story will appear here...
How the Code Works:
- We collect different words from the user using prompt()
- We check if the user canceled any of the prompts with if(word === null)
- We use template literals (backticks) to insert the user's words into our story
- We return the completed story to be displayed
Extend the Game!
Try adding more prompts and expanding the story. Can you make it even funnier?
// Add these to collect more words let adjective2 = prompt("Enter another adjective:"); let noun2 = prompt("Enter another noun:"); // Then expand your story let expandedStory = `${story} The ${noun1} was incredibly ${adjective2} and demanded a ${noun2}!`;
When NOT to Use prompt()
Professional Applications
As Grumpy and Garbage pointed out, prompt() isn't suitable for professional applications because:
- It blocks the entire page execution
- It can be blocked by browsers
- It has poor user experience
- It can't be styled to match your site
- It's not accessible for screen readers
Better Alternatives
For real applications, use these alternatives:
- HTML form inputs with JavaScript validation
- Custom modal dialogs
- React/Vue/Angular form components
- For passwords specifically:
<input type="password"> - For complex input: dedicated form libraries
// Instead of: let password = prompt("Enter your password:"); // Use HTML like this: /* <form> <label for="password">Enter your password:</label> <input type="password" id="password" name="password"> <button type="submit">Submit</button> </form> // Then access with JavaScript: document.querySelector('form').addEventListener('submit', function(event) { event.preventDefault(); const password = document.getElementById('password').value; // Process password here }); */
Chapter 5, Episode 5: Key Takeaways
Basic Syntax
The prompt() function displays a dialog box that prompts the user for input.
Return Value
prompt() returns the text entered by the user as a string, null if canceled, or an empty string if nothing was entered.
Type Conversion
Remember to convert the string return value to a number if you need to perform mathematical operations.
Best Uses
prompt() is best used for learning and simple applications. For production applications, use HTML forms and other input methods.
Interactive Applications
Despite its limitations, prompt() is a great way to make interactive applications when learning JavaScript, like our Mad Libs game!
Now that we understand prompt(), we can build more interactive applications and collect user input. In the next episode, we'll learn how to use console.log() for debugging our code.
Up Next in Chapter 5
Console Logging
Debugging with console
Conditionals
if/else statements
Snowzie McTweak
Woof! *happily paws at keyboard, commits code*
CODE IS COMMITTED!