McTweak.ai

Learn to code with the McTweak Family!

Chapter 5: JavaScript Basics - Episode 5

User Input with prompt()

Chapter 5 Progress Episode 5 of 10
Ashley McTweak

Ashley McTweak

Our new security system needs a password input, but all I've got is this broken code from some bootcamp graduate who thinks 'prompt' is what you do at a theater performance.

Ally McTweak

Let me see the damage. *leans in to read* Oh honey, this isn't just broken, this is what happens when Stack Overflow vomits on a keyboard.

Ally McTweak
Cody McTweak

Cody McTweak

M-maybe we could just use the free version? You know, like, no security at all? That's kind of my specialty...

Ashley McTweak

Ashley McTweak

The last time we used your "specialty," someone hacked our system using nothing but a refrigerator magnet and a strongly worded email.

Fatty McTweak

Did someone say 'security breach'? *looks at screen* Let me guess - another JavaScript prompt problem? *sighs dramatically* Watch and learn, peasants. This is what premium-tier problem solving looks like.

Fatty McTweak

Fatty McTweak

See, what you NEED is to capture user input elegantly. prompt() is like the doorman of JavaScript - it stops everything until the user responds, which is exactly what you want for a password system.

Fatty McTweak
Ashley McTweak

Ashley McTweak

I'm not sure stopping the entire application is what we—

Fatty McTweak

*interrupting* Shhh! My genius is flowing. Don't interrupt the process.

Fatty McTweak
Grumpy McTweak

Grumpy McTweak

What fresh security NIGHTMARE is happening here? *peers at screen* You're using PROMPT for PASSWORD input?! ARE YOU TRYING TO INVITE HACKERS TO A GODDAMN POTLUCK IN OUR DATABASE?

Fatty McTweak

*defensively* It's just a prototype! Besides, my implementation is flawless.

Fatty McTweak
Grumpy McTweak

Grumpy McTweak

*mockingly* Oh sure, flawless like the Titanic's "unsinkable" design. prompt() shows the input in PLAIN TEXT! It's like asking users to shout their passwords through a megaphone in a crowded mall!

Trashy McTweak

*laughs* Look at all you dinosaurs arguing about prompt(). What's next, are we gonna debate the merits of alert() for data visualization?

Trashy McTweak
Ally McTweak

Ally McTweak

*sarcastically* Please, enlighten us with your revolutionary input solution, oh coding messiah.

Trashy McTweak

Two words: VOICE RECOGNITION. *makes explosion gesture with hands* BOOM! Mind blown, right?

Trashy McTweak
Grumpy McTweak

Grumpy McTweak

*fuming* So instead of showing passwords on screen, you want users to ANNOUNCE them out loud? BRILLIANT! Let's just install loudspeakers in the parking lot while we're at it!

Trashy McTweak

*deflated* Well, when you put it that way...

Trashy McTweak
Garbage McTweak

Garbage McTweak

*sighing deeply* You're all overthinking this. prompt() is fine for learning, terrible for production. *walks to computer, types briefly* There. A simple password field with proper masking. Now can I go back to my game? I was THIS close to defeating the Elden Beast.

Fatty McTweak

*whispers* I was about to do exactly that.

Fatty McTweak
Trashy McTweak

Trashy McTweak

*whispers back* Sure you were, big guy.

Garbage McTweak

Snowzie's right. The real magic of prompt() isn't for passwords - it's for teaching beginners how to collect user input for fun stuff, like Mad Libs.

Garbage McTweak
Cody McTweak

Cody McTweak

*brightening* Mad Libs? Even I could help with that!

Snowzie McTweak

Snowzie McTweak

Woof! *paws at keyboard enthusiastically*

Garbage McTweak

Looks like we have today's lesson plan. Mad Libs it is.

Garbage McTweak

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:

  1. We collect different words from the user using prompt()
  2. We check if the user canceled any of the prompts with if(word === null)
  3. We use template literals (backticks) to insert the user's words into our story
  4. 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

1
Basic Syntax

The prompt() function displays a dialog box that prompts the user for input.

2
Return Value

prompt() returns the text entered by the user as a string, null if canceled, or an empty string if nothing was entered.

3
Type Conversion

Remember to convert the string return value to a number if you need to perform mathematical operations.

4
Best Uses

prompt() is best used for learning and simple applications. For production applications, use HTML forms and other input methods.

5
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

6

Console Logging

Debugging with console

7

Conditionals

if/else statements

Previous Episode Next Episode
Snowzie McTweak

Snowzie McTweak

Woof! *happily paws at keyboard, commits code*

CODE IS COMMITTED!