How to Display Alert in JavaScript: Simple Guide
To display an alert in JavaScript, use the
alert() function with a message inside parentheses and quotes, like alert('Hello!'). This shows a popup box with the message to the user.Syntax
The basic syntax to show an alert is alert(message).
- alert: The function that creates the popup.
- message: The text you want to show, written inside quotes.
javascript
alert('Your message here');Output
A popup alert box with the text: Your message here
Example
This example shows a simple alert with the message 'Hello, world!'. When you run it, a popup box appears with that text.
javascript
alert('Hello, world!');Output
A popup alert box with the text: Hello, world!
Common Pitfalls
Common mistakes include forgetting the quotes around the message or missing the parentheses. Also, alerts can be annoying if overused, so use them sparingly.
javascript
/* Wrong: missing quotes around message */ // alert(Hello); /* Correct: quotes included */ alert('Hello');
Output
A popup alert box with the text: Hello
Quick Reference
| Usage | Description |
|---|---|
| alert('text') | Shows a popup alert with the given text. |
| alert(123) | Shows a popup alert with the number 123. |
| alert(true) | Shows a popup alert with the text 'true'. |
Key Takeaways
Use alert('message') to show a popup message in JavaScript.
Always put the message inside quotes to avoid errors.
Alerts pause code execution until the user clicks OK.
Avoid overusing alerts as they can annoy users.
alert() works in all modern browsers without extra setup.