Skip to content
Home ยป JavaScript Tutorial Exercise 7: User interaction and alert prompt

JavaScript Tutorial Exercise 7: User interaction and alert prompt

JavaScript allows developers to create interactive web applications by responding to user input. Even a simple function can demonstrate several important programming concepts, including functions, variables, conditional statements, user interaction and template literals.

In this tutorial, we will create a JavaScript function that asks users for their name and displays a personalized greeting.

1. The JavaScript Code

Let’s start by examining the complete function.

function greetUser() {
    const name = prompt("What is your name?");
    if (name) {
        alert(`Hello ${name}! Nice to meet you.`);
    } else {
        alert("You did not provide your name. Please try again.");
    }
}

The function is called greetUser() and performs three main operations.

  1. Requests the user’s name.
  2. Checks whether the user provided a value.
  3. Displays an appropriate message.

Although the function is relatively short, it introduces several fundamental JavaScript concepts.

2. Defining a Function

The first line declares a function named greetUser.

function greetUser() {

In JavaScript, a function is a reusable block of code designed to perform a particular task.

The function keyword declares the function, while greetUser is its name.

The parentheses () indicate that the function does not require any parameters.

The curly braces {} contain the instructions that will execute when the function is called.

To execute the function, we simply write:

greetUser();

An important distinction is that declaring a function does not automatically execute it. The function must be called explicitly or triggered by an event.

3. Requesting User Input with prompt()

The next instruction asks the user to enter their name.

const name = prompt("What is your name?");

The built-in JavaScript prompt() method displays a dialog box containing a message and a text input field.

The user can enter a value and confirm it by clicking OK.

The result is stored in a variable named name.

We use the const keyword because the variable will not be reassigned during the execution of the function.

The prompt() method can return two types of values:

  1. A string containing the user’s input when OK is selected.
  2. null when the user cancels the dialog.

If the user clicks OK without entering anything, the method returns an empty string ("").

These distinctions become important when validating user input.

4. Validating Input with an if Statement

After requesting the user’s name, the function checks whether a value was provided.

if (name) {

The if statement evaluates the value of the name variable in a Boolean context.

JavaScript automatically converts the value into either true or false. This process is known as truthy and falsy evaluation.

For example:

InputBoolean evaluation
"John"true
"Alice"true
""false
nullfalse
" "true

Notice that a string containing only spaces evaluates to true.

This means that our original function accepts whitespace as a valid name. We will address this limitation later in the tutorial.

5. Displaying a Personalized Greeting

When the user provides a truthy value, the following instruction executes:

alert(`Hello ${name}! Nice to meet you.`);

The alert() method displays a browser dialog containing a message.

However, the most interesting part of this instruction is the use of a JavaScript template literal.

Template literals use backticks instead of traditional single or double quotation marks.

They allow developers to insert expressions directly into strings using the ${} syntax.

For example:

const name = "John";

console.log(`Hello ${name}!`);

Output:

Hello John!

Without template literals, we could write the same message using string concatenation:

alert("Hello " + name + "! Nice to meet you.");

Both approaches produce the same result, but template literals generally improve readability, particularly when a string contains multiple variables.

6. Handling Missing Input with else

What happens when the user clicks Cancel or submits an empty string?

The if condition evaluates to false, so JavaScript executes the else block.

else {
    alert("You did not provide your name. Please try again.");
}

This provides basic input validation and ensures that the user receives feedback when no name is supplied.

The if...else structure is one of the most common control flow mechanisms in JavaScript.

It allows a program to select between different execution paths depending on whether a condition is satisfied.

7. Improving the Function

Our original implementation works, but we can improve it by handling whitespace and distinguishing between cancelled input and empty input.

Consider the following version:

function greetUser() {
    const name = prompt("What is your name?");

    if (name === null) {
        alert("You cancelled the operation.");
    } else if (name.trim() === "") {
        alert("Please enter a valid name.");
    } else {
        alert(`Hello ${name.trim()}! Nice to meet you.`);
    }
}

This implementation introduces two additional concepts.

Strict equality (===)

The expression name === null checks whether the user cancelled the prompt.

Strict equality compares values without performing type coercion.

The trim() method

The trim() method removes whitespace from the beginning and end of a string.

For example:

const name = "   John   ";

console.log(name.trim());

Output:

John

By combining trim() with an empty string comparison, we can reject input consisting entirely of spaces.

The improved function now handles three situations: cancelled input, empty input and valid input.

8. Running the Function in a Web Page

We can integrate the function into a simple HTML document and execute it when a user clicks a button.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JavaScript Greeting Example</title>
</head>
<body>

    <h1>JavaScript Greeting Example</h1>

    <button onclick="greetUser()">
        Greet Me
    </button>

    <script>
        function greetUser() {
            const name = prompt("What is your name?");

            if (name && name.trim()) {
                alert(`Hello ${name.trim()}! Nice to meet you.`);
            } else {
                alert("Please enter your name.");
            }
        }
    </script>

</body>
</html>

Save this code as index.html and open it in a web browser.

Clicking the Greet Me button executes the function.

The onclick attribute associates the button with a JavaScript function. This is an example of event-driven programming, where code executes in response to user actions.

For larger applications, using addEventListener() is generally preferable because it separates JavaScript behavior from HTML structure.

9. Testing the Function

Even a small function should be tested against different input scenarios.

The following test cases help verify its expected behavior.

Test caseUser inputExpected result
TC01JohnPersonalized greeting
TC02AlicePersonalized greeting
TC03Empty stringValidation message
TC04Spaces onlyValidation message in improved version
TC05CancelCancellation message in improved version
TC06John SmithGreeting containing full name

These tests cover normal input, boundary conditions and alternative user actions.

The original implementation will fail TC04 because whitespace is considered truthy. The improved implementation correctly rejects whitespace-only input.

This demonstrates how testing can reveal limitations even in relatively simple code.

10. Conclusion

The greetUser() function is an example of how JavaScript can interact with users.

Despite its simplicity, it introduces several essential programming concepts:

  1. Creating and executing reusable functions.
  2. Declaring variables using const.
  3. Requesting user input with prompt().
  4. Controlling program execution with if...else.
  5. Displaying messages using alert().
  6. Creating dynamic strings with template literals.
  7. Validating input and handling unexpected values.

Understanding these concepts provides a foundation for developing more sophisticated interactive web applications.

While prompt() and alert() are useful for learning JavaScript, modern web applications typically use HTML forms and dynamically updated page elements to provide a more flexible and user-friendly experience.

The next logical step is to replace the browser dialogs with an HTML input field and display the personalized greeting directly on the web page.

Leave a Reply

Your email address will not be published. Required fields are marked *