Last updated: Mar 7, 2024
Reading time·5 min
You can use the addition (+) operator to display a variable value in an alert box.
The addition operator will concatenate the alert message and the variable and will display the entire string.
Here is an example HTML page that loads a JavaScript index.js
file.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> <script src="index.js"></script> </body> </html>
And here is the code for the index.js
file.
const fullName = 'Bobby Hadz'; alert('Employee name: ' + fullName);
We used the addition (+) operator operator to concatenate the string and the variable.
You can use this approach to concatenate the alert message with as many variables as necessary.
const first = 'Bobby'; const last = 'Hadz'; alert('Employee name: ' + first + ' ' + last);
An alternative approach is to use a template literal.
Note that template literal strings are enclosed in backticks ``, not in single quotes.
const first = 'Bobby'; const last = 'Hadz'; alert(`Employee name: ${first} ${last}`);
You can use the dollar sign ${}
curly braces syntax to interpolate variables
in the alert message.
Make sure to use backticks `` and not single quotes when wrapping the alert message for the template string to work as expected.
If you try to display an object or an array of objects in an alert box, you'd get an "[object Object]" value back.
const obj = { id: 1, name: 'Bobby Hadz', age: 30, }; alert(obj);
The "[object Object]" value is not very useful.
The alert() function tries to convert the object to a string and prints "[object Object]".
You can use the JSON.stringify()
method to print the actual value of the
object.
const obj = { id: 1, name: 'Bobby Hadz', age: 30, }; alert(JSON.stringify(obj));
The JSON.stringify() method converts a JavaScript value to a JSON string.
If you need to print a message and an object or array variable, use a template literal.
const obj = { id: 1, name: 'Bobby Hadz', age: 30, }; alert(`Employee object: ${JSON.stringify(obj)}`);
If you need to display variables in an Alert box on separate lines, use a template literal.
const first = 'Bobby'; const last = 'Hadz'; const age = 30; alert(`First Name: ${first} Last Name: ${last} Age: ${age}`);
New lines are preserved when using template literals, so you can just write your alert message spanning multiple lines.
Note that template literals are enclosed in backticks `` and not single quotes.
Let's look at an example of displaying an alert with a variable on button click.
Here is the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> <button id="btn">Click</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const fullName = 'Bobby Hadz'; const button = document.getElementById('btn'); button.addEventListener('click', event => { alert('Name: ' + fullName); });
We added a click
event listener to the button, so every time it's clicked, we
call the alert()
function with a message and a variable.
Alternatively, you can add the onclick
event listener online, in your HTML
code to not have to write your JavaScript separately.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <script> const fullName = 'BobbyHadz'; function myFunction() { alert('Name: ' + fullName); } </script> </head> <body> <div>bobbyhadz.com</div> <button id="btn" onclick="myFunction()">Click</button> </body> </html>
The code sample achieves the same result without using an external JavaScript file.
Let's look at an example of displaying variables from form fields using the
alert()
function.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div>bobbyhadz.com</div> <form id="form"> <input type="text" id="first" placeholder="First name: " /> <input type="text" id="last" placeholder="Last name: " /> <button id="btn" type="submit">Submit</button> </form> <script src="index.js"></script> </body> </html>
Here is the related JavaScript code.
const form = document.getElementById('form'); form.addEventListener('submit', event => { event.preventDefault(); const first = document.getElementById('first').value; const last = document.getElementById('last').value; if (first.trim() === '' || last.trim() === '') { alert('The fields are required.'); } else { alert(`Name: ${first} ${last}`); } });
We used the event.preventDefault()
function to prevent the page refresh when
the form is submitted.
We selected the first
and last
input fields and accessed their values.
The last step is to call the alert()
function with the message and the
variables.
The function uses an if/else
statement to alert the user that the fields are
required if they forget to enter a value.
You can achieve the same result without an external JavaScript file, by using an inline event listener.
Here is the HTML and JavaScript code for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <script> function alertFormValues() { const form = document.getElementById('form'); const first = document.getElementById('first').value; const last = document.getElementById('last').value; if (first.trim() === '' || last.trim() === '') { alert('The fields are required.'); } else { alert(`Name: ${first} ${last}`); } } </script> </head> <body> <div>bobbyhadz.com</div> <form id="id" onsubmit="alertFormValues()"> <input type="text" id="first" placeholder="First name: " /> <input type="text" id="last" placeholder="Last name: " /> <button id="btn" type="submit">Submit</button> </form> </body> </html>
We wrote the JavaScript code in a script
tag, so no external JS code is
loaded.
The code alerts the input field's value from the form without using any external JavaScript files.
I've also written an article on how to edit the Title of an Alert Box in JavaScript.