How to Display a Variable in an Alert Box in JavaScript
The alert() function is a simple way to display information to a user in a modal dialog. A common use case is to show the value of a variable, which is essential for debugging or communicating status. The best modern approach for this is to use template literals, which provide a clean and readable way to embed variables directly into strings.
This guide will teach you the best methods for displaying variables in an alert box. You will learn how to use template literals for single and multi-line messages, and how to correctly display complex data types like objects and arrays.
The Modern Method (Recommended): Template Literals
Template literals are the most readable and powerful way to construct strings in modern JavaScript. They are enclosed in backticks (`) and allow you to embed expressions and variables directly into the string using the ${expression} syntax.
For example, you have a variable and want to display it in a user-friendly message.
// Problem: How to show this name in an alert?
const fullName = 'Alice';
Solution:
const fullName = 'Alice';
// Use backticks and the ${} syntax to embed the variable.
alert(`Welcome, ${fullName}!`);
This is the recommended best practice because it is clean, easy to read, and avoids the clumsiness of the older + operator.
The Classic Method: String Concatenation with +
Before template literals were introduced, the standard way to build strings was by "concatenating" (joining) them with the addition (+) operator. This method is still functional but is more verbose and less readable.
Solution:
const fullName = 'Alice';
const age = 30;
// Use the + operator to join the strings and variables.
alert('User: ' + fullName + ', Age: ' + age);
As you can see, this requires manually adding spaces and can become difficult to read with multiple variables.
How to Display Objects and Arrays in an Alert
If you try to display a non-primitive value like an object or an array directly in an alert(), you will get a generic and unhelpful message.
const user = { id: 1, name: 'Alice' };
alert(user); // Output: [object Object]
In the example above, the alert() function tries to convert the object to a string, resulting in the default [object Object] representation.
The solution is to use JSON.stringify(): to display the actual content of an object or array, you must first convert it to a JSON string using the JSON.stringify() method.
const user = { id: 1, name: 'Alice', roles: ['admin', 'editor'] };
// Use JSON.stringify to get a readable string representation.
alert(JSON.stringify(user, null, 2));
The extra arguments (null, 2) "pretty-print" the JSON with indentation, making it easier to read in the alert box. You can combine this with a template literal for a complete message:
alert(`User data: ${JSON.stringify(user, null, 2)}`);
How to Display a Multi-Line Alert
Template literals also make it incredibly easy to create multi-line strings. Any new line you create inside the backticks will be preserved in the final output.
const firstName = 'Alice';
const lastName = 'Smith';
const role = 'Administrator';
alert(`User Profile:
First Name: ${firstName}
Last Name: ${lastName}
Role: ${role}
`);
This is far cleaner than the older method of using the newline character (\n) with the + operator.
Practical Example: Showing Form Input in an Alert
A very common use case is to get values from form input fields and display them in a confirmation alert.
HTML:
<form id="myForm">
<input type="text" id="username" placeholder="Username">
<button type="submit">Submit</button>
</form>
JavaScript:
const form = document.getElementById('myForm');
const usernameInput = document.getElementById('username');
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevent the page from reloading
const username = usernameInput.value;
if (username.trim() === '') {
alert('Username is required.');
} else {
alert(`Thank you for submitting, ${username}!`);
}
});
Conclusion
Displaying variables in a JavaScript alert() is a simple task, and using the right technique can make your code much cleaner.
- The recommended best practice is to use template literals (
`). They are highly readable, handle multiple variables and multi-line strings effortlessly, and are the modern standard. - When displaying objects or arrays, always convert them to a string first using
JSON.stringify()to get a useful output. - Avoid the older
+operator for string concatenation when possible, as it is more verbose and less readable than template literals.