An alert box is a pop-up message box that displays an alert message to the user. It can be used to inform the user about an error or to display a message. It’s helpful to use to debug code that may not be executing correctly.
Here’s how you can create an alert box in JavaScript:
- Open your code editor and create a new HTML file.
- Add a button to your HTML file. For example:
<button onclick="alert('Hello, World!')">Click me</button>
- The
onclick
attribute will trigger the alert box when the button is clicked. - Save the HTML file with a
.html
extension and open it in your web browser. - Click the button, and you should see an alert box with the message “Hello, World!”. You can change that text to anything you want.*
If done correctly, the above code will produce this:
*Pressing enter and going to a new line in the quotations will cause the alert box to break. So while the above code will work, the following will not:
<button onclick="alert('Hello,
World!')">Click me</button>
To get around that, you’ll need to do a new line escape sequence using \n:
<button onclick="alert('Hello, \n World!')">Click me</button>
There you have it, your very first JavaScript code!