How to use alert to display variables in JavaScript

Updated onbyAlan Morel
How to use alert to display variables in JavaScript

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.

JAVASCRIPT
const 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.

JAVASCRIPT
const 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:

JAVASCRIPT
const name = "sabe.io"; const age = 20; alert(`My name is ${name}.\nI am ${age} years old.`);

This displays:

BASH
My 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.

JAVASCRIPT
const 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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.