Alert Method in JavaScript
Alert Method in JavaScript
JavaScript
The users will not be able to access the program’s interface until they click the OK button,
confirming that they have read the message.
Basic examples
Below is a basic example of creating an alert using JavaScript:
alert('Please read our terms and conditions');
This line of code will display an alert window containing the words “Please read our terms
and conditions”, along with a button that reads “OK”. This syntax is also equivalent to the
following code:
window.alert('Please read our terms and conditions');
This code performs the same task as the first example, but explicitly uses the window object
to generate the alert.
Syntax
The syntax for the Window.alert() method is as follows:
alert(message)
message (optional): a String specifying the text that will appear in the popup box. This
message will appear above an “OK” button. If data types other than Strings are provided as
the message parameter, the alert() method will try to convert the data into a string by
applying the toString() method.
undefined
alert(undefined);
// Expected text message: undefined
null
alert(null);
// Expected text message: null
Array
alert([22, 15, 67]);
// Expected text message: 22, 15, 67
Note: The square brackets are removed from the array during the string conversion process.
Object
const user = { name: 'John', age: 36 };
alert(user);
// Expected text message: [object Object]
When alerting with a Symbol we receive a TypeError. To get around this, apply
the toString() method to the symbol as seen below:
alert(sym.toString())
// Expected text message: Symbol(foo)
Related Articles:
JavaScript – How to Use the toString method
JavaScript – How to Use JSON.stringify
JavaScript – How to Use the for…in Statement
Related Posts