How to use alert to display variables in JavaScript
Table of Contents
Because JavaScript was designed primarily for use on the browser on the front-end, it contains some useful built-in functions that are more visual in nature.
One of these functions include the alert
function.
In this post, we'll learn how to use the alert
function to display variables to the user.
How to use the alert function to display a single variable
The illustrate how to use the alert
function, let's use it to display a single variable.
The alert
function takes a single argument, which is the string that you want to display to the user.
JAVASCRIPTconst name = "sabe.io";
alert(name);
This code will open a dialog box with the text sabe.io
in it, as expected.
This is useful when developing a web app and you want to debug the value of a variable, or to display a message to the user.
How to use the alert function to display multiple variables
Because the alert
function only takes a single argument, we will have to construct a string ourselves that contains all the variables we want to display.
We can use a template literal to do this, and interpolate the variables into the string.
JAVASCRIPTconst name = "sabe.io";
const age = 20;
alert(`My name is ${name} and I am ${age} years old.`);
This code will open a dialog box with the text My name is sabe.io and I am 20 years old.
in it.
We can even use the \n
new line character to display these on separate lines:
JAVASCRIPTconst name = "sabe.io";
const age = 20;
alert(`My name is ${name}.\nI am ${age} years old.`);
This displays:
BASHMy name is sabe.io.
I am 20 years old.
How to use the alert function to display an object or array
As with before, because the alert
function only takes a string, we will have to convert the object or array into a string ourselves.
The easiest way to do this is to just use the JSON.stringify
function.
JAVASCRIPTconst person = {
name: "sabe.io",
age: 20
};
alert(JSON.stringify(person, null, 4));
This will display:
JSON{
"name": "sabe.io",
"age": 20
}
Conclusion
In this post, we learned how to use the alert
function to display variables to the user.
We learned how to display a single variable, multiple variables, and even objects and arrays.
Thanks for reading!
- Getting Started with TypeScript
- Getting Started with Svelte
- How to deploy a .NET app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- Getting Started with Sass
- Using Puppeteer and Jest for End-to-End Testing
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- How To Create a Modal Popup Box with CSS and JavaScript