Difficulty: Easy
Correct Answer: An alert box displays a message with an OK button only, while a confirmation box displays a message with OK and Cancel buttons and returns a boolean value.
Explanation:
Introduction / Context:
JavaScript provides simple built in dialog functions for basic user interaction: alert, confirm, and prompt. Understanding the behavioral differences between alert boxes and confirmation boxes is important for implementing user flows such as warnings and yes/no decisions without building custom dialogs.
Given Data / Assumptions:
Concept / Approach:
The alert function is purely informational. It shows a message, waits for the user to press OK, and then returns undefined. It cannot directly capture a yes/no decision. The confirm function, on the other hand, is intended to ask the user to confirm or cancel an action. It displays two buttons, OK and Cancel, and returns true when the user clicks OK and false when the user clicks Cancel or dismisses the dialog. Both dialogs are blocking and modal in most browsers, temporarily stopping script execution until the user responds.
Step-by-Step Solution:
Verification / Alternative check:
A developer can test these functions directly in the browser console. Calling alert('Hello') shows a single button dialog and does not yield a true/false result. Calling confirm('Delete item?'), assigning the result to a variable, and then logging it reveals true or false depending on which button the user clicks, demonstrating the behavioral difference clearly.
Why Other Options Are Wrong:
Common Pitfalls:
One pitfall is overusing alert and confirm in production code, which can annoy users and block interaction. Another mistake is forgetting to use the boolean result from confirm and assuming OK was always chosen. Modern applications often replace these dialogs with custom modal components built using HTML, CSS, and JavaScript for better styling and control.
Final Answer:
The correct choice is An alert box displays a message with an OK button only, while a confirmation box displays a message with OK and Cancel buttons and returns a boolean value. because this clearly describes the visual and behavioral differences between the two dialog types in JavaScript.
Discussion & Comments