Alert syntax in JavaScript

In this tutorial, we’ll be looking at the alert syntax in JavaScript. Let’s look at the different ways of using alert boxes to display messages and information on your browser screen.

The alert function is a pre-defined function in JavaScript. It accepts one argument, and it displays whatever information is given to it, at the time we specify. This could be right after the page loads, when an element is clicked, or after some time has lapsed. You need to set those conditions.

Let’s look at different ways of using the alert box.

Displaying a message

The syntax for displaying an alert box is as follows:

window.alert(message);

So, you’ll be displaying an alert box, and inside the alert box, whatever’s specified inside “message” will be displayed. That’s how it works.

Let’s replace message with an actual string, say “Hello there!”, like this:

window.alert("Hello there!");

If you run the above line of code, this is what you’ll see on your browser screen:

alert syntax in javascript

Remember that the string specified inside the alert() function call should be within quotes, either single or double quotes. Otherwise, the browser will think it’s a variable, and it’ll try to retrieve it, and when it can’t, it’ll either throw an error, or show “undefined” in place of those letters.

To display alert in current window

You can also write the alert box syntax without including “window”, which would mean that the alert box will be displayed in the current window.

This is how the syntax is written:

alert(message)

Let’s replace the “message” part of it with a string that can be displayed.

alert("Hello! This is a message!");

When we run the above line of code, this is the output we get:

javascript alert syntax

So, that’s the simplest way of using an alert box to display a basic text-based message. What if you want to do more than that with it?

 

Custom message from a variable

You can give custom messages inside the alert box. You don’t have to directly give a string as a parameter. You can assign a string to a variable and give that variable as a parameter inside your alert function call.

Let’s create a variable called “message” and assign it a string “This is the message”.

var message = "This is the message";

Now, instead of the string, give “message”, without quotes, as the parameter inside the alert call.

alert(message);

When you run the above lines of code, this is the output you’ll get:

javascript alert box

As you can see, this works just as well as directly inputting a string does.

 

Display alert message with line breaks

What if you want to display your alert message with line breaks? What if you want them to be displayed over couple of lines, rather than stuffing them all into one line?

Then, you can use the newline character to create a new line after your first line. “\n” (without quotes) is what you’ll use to create new lines.

Let’s see how we can use it in an example of our own:

alert("Hi there! \nHow have you been?");

When we run the above line of code, this is what we’ll get:

javascript window alert

As you can see, “Hi there!” is in a separate line and “How have you been?” is in the next line because you inserted “\n” before it. Don’t leave a space between “\n” and the next line. Otherwise, you’ll get a space before that line starts.

You can insert as many new lines as you want in a single alert statement. That’s completely up to you.

 

Performing and displaying calculations on an alert box

The alert box is not just for displaying strings and text messages
.
You can also perform calculations within the function call and display the output in the alert box.

Let’s do a basic 5 + 6 calculation inside our alert box and see what we get.

alert(5 + 6);

If you run the above line of code, your alert box will display the number 11 on your browser screen.

javascript alert example

Displaying calculations with variables

Just like with strings, you don’t have to stick to directly inputting the numbers and operators inside the alert function call. You can create variables and assign your numbers or operators to them and use them in your alert call as well.

Let’s create 2 variables, a and b, and assign the same number 5 to both.

var a = 5;
var b = 5;

Then, let’s input a + b in the alert call.

alert(a + b);

When we run the above lines of code, we’ll get a 10 in our alert box.

javascript alert function

Combining both calculations and text

Let’s try to concatenate both the string and the calculation and see what we get.

alert("The result of a + b = " + a + b);

alert message in javascript

When you run the above line of code, you get: “The result of a + b = 55”

Concatenation of a string and a number is a string, so a becomes a string, then b becomes a string, so the entire thing becomes string concatenation.

alert("The result of a + b = " + (a + b));

Adding parentheses around the part where the calculation needs to happen will keep them separate from the string. (a+b) will be calculated first, and we’ll get the output 10.

Then, the string will be concatenated with 10, which will now become a string and we’ll get the following output, which is exactly what we expected:

js alert box

 

Displaying multiple variables and strings displayed on an alert box

As you probably guessed, you can intersperse variables with strings in an alert box as well. This will make the alert box more dynamic because you can change the values inside the variables and automatically have them updated in your alert boxes.

Let’s create a bunch of variables: name, age, height and weight. Let’s assign “John”, 38, 180 and 200 as values to these variables.

var name = "John";
var age = 38;
var height = 180;
var weight = 200;

Now, I essentially want to display this message in the alert box: “John is 38 years old, 180 cms tall and weighs 200 lbs.”

How would I do that?

I’ll use string concatenation, of course! I’ll use the “+” operator to join the variables with the strings, because “John” will be the “name” variable’s value, but “ is “ is just a string, so I need to concatenate both to get “John is”, and so on.

I’ll follow the same procedure for the other variables and pieces of strings as well. Let’s see how it all comes together.

alert(name + " is " + age + " years old, " + height + "cms tall, and weighs " + weight + "lbs.");

If I run the above lines of code, I’ll get the output I wanted to see.

javascript alert variable

 

Alert messages within loops

You can also place an alert function call within a loop, so you get new alert boxes every time you click the “ok” button. These boxes will keep popping up until the loop executes.

Let’s demonstrate this with a for loop. Let’s run the loop until i = 0 to 9, so 10 times. Every time, we’ll alert the “i” value in the alert box.

for(var i=0; i<10; i++) {
	alert(i);
}

When you run the above line of code, you’ll first see the following alert message:

javascript alert title

Then, when you click on the “ok” button, you’ll get the following message:

js window alert

And that’s how it’ll go for 2, 3, 4 and so on until we reach 9.

alert button javascript

The same example can be replicated with other loops like the while loop and do while loop.

You can also use alert boxes in “if” statements to display different messages based on whether the if condition is true or not.

 

Displaying alert boxes on button clicks with onclick()

As I said before, you can make the alert box appear when an event happens. For example, when the user clicks on a button, the alert message you’ve specified should appear. You can create a code like this. Let’s look at different ways of doing that.

The easiest way to achieve this is by using the onclick function call within the button you’re creating. You can do this by sending parameters inside the function call or without. Let’s look at calling a function without parameters first.

Without parameters

So, let’s create a basic HTML skeleton, and when we create the button, we’ll create an “onclick” event, and assign a function call to it. This basically means that whenever that button is clicked on, the specified function will be called.

<!DOCTYPE html>
<html lang="en">
<head>
	<title>JavaScript for beginners</title>
</head>
<body>
	<button onclick="clickButton()">Click me!</button>
	<script src="script.js"></script>			
</body>
</html>

If you noticed, the function call is encased within double quotes. This is compulsory. Your onclick function call won’t work if the quotes are missing. You can either use double quotes or single quotes.

Now that we’ve created the HTML part of things, let’s create the function in the script.js file.

Inside the function’s definition, we’ll create an alert message that says “Hi! You’ve clicked me!”.

function clickButton() {
	alert("Hi! You've clicked me!");
}

When you run the program, you’ll see the “Click me!” button on the screen.

javascript onclick alert

When you click on the button, an alert box will pop up, like this:

html onclick alert

You can make this alert box do anything. It doesn’t just have to display messages. It can display values of variables, do calculations, etc. Use your imagination or do what’s required of your program.

With parameters

As I said before, you can also call the function and send parameters in them. Let’s try to send a person’s name as our parameter.

You can’t just send the parameter though. Every parameter should be encased within quotes. Since we use double quotes in our function call, encase the parameter to be sent to the function within single quotes. This only applies to strings. If your parameter is a number, it doesn’t have to be specified within quotes.

If you used single quotes in your function call though, the parameter should be encased in double quotes, to distinguish between the function call and the parameter.

So, let’s create an onclick, and assign a clickButton function call to it, and send “John Doe” as the parameter within it.

<button onclick="clickButton('John Doe')">Click me!</button>

Now, let’s create the clickButton function and accept the sent parameter within the “name” variable, and display it in the alert message.

function clickButton(name) {
	alert("Hi " + name + "! You've clicked me!");
}

Let’s run the above lines of code, and this is what we’ll get:

onclick alert with parameters

Sending multiple parameters in the onclick call

You can also send more than one parameter within your function call. You’ll just need to separate them by commas.
As I told you before, if the parameters are numbers, they can be specified as is.

<button onclick="clickButton('John Doe', 38)">Info</button>

Let’s accept both the parameters sent from the function call above and use it to create an alert message.

function clickButton(name, age) {
	alert(name + " is " + age + " years old.");
}

This is the output we’ll get:

javascript onclick alert with multiple parameters

 

Displaying alert on click of a button with addEventListener

Even though onclick is the easiest way of creating an alert popup when a click event happens, it’s not the professional way of doing things.

If you want to do things professionally, you’ll need to use an addEventListener. The good thing about an event listener is that you can create function calls for not just a click event, but various other events like mouseover, mousedown, mouseup and so on.

Let’s look at the click event in this example. The process is the same for the other events as well.

Let’s first create a button. This time, we won’t be creating an onclick event, but we would need to assign an id for our button so it can be referenced from the script.js file.

<button id="button1">Click Me!</button>

Now, in the script.js file, we’ll first create a “name” variable that’ll hold the value “John Doe”. We’ll be using this variable in our alert message later.

var name = "John Doe";

Now, let’s create another variable “button1” and use the getElementById method to retrieve the “button1” button we created in our HTML document.

var button1 = document.getElementById("button1");

Now, our button1 variable has the button1 HTML element inside it. Let’s create an addEventListener method for “button1”.

This call accepts 2 parameters. The first parameter specifies which even you are creating an event listener for.
In our case, it’s the “click” event. This should be specified within quotes (double or single quotes).

The second parameter is the function call. The only difference between this function call and the rest is that you just specify the function, without the parenthesis like you usually do.

So, let’s create a click event listener and call the infoDisplay function from the call.

button1.addEventListener("click", infoDisplay);

Now, let’s create the function and within the function, we’ll display an alert box that displays a custom message.

function infoDisplay() {
	alert("You've clicked on the button. Your name is " + name);
}

When we run the above lines of code, this is what we’ll get:

addEventListener alert box

So, instead of creating a function definition separately by just calling the function from the event listener, you can also create an anonymous function right from inside the event listener.

Let’s see how to do that:

var name = "John Doe";
var age = 38;
var button1 = document.getElementById("button1");
button1.addEventListener("click", function() {
	alert("You've clicked on the button. Your name is " + name + ".\nYour age is " + age);
});

So, instead of the function call, just create a function(), which is an anonymous function, and within it, create the alert message you want. I’ve also used a “\n” to separate the lines in our alerts.

addEventListener alert box anonymous function

So, that’s it! We’ve looked at plenty of ways of using the alert boxes in JavaScript, and the alert syntax for each of those methods. Hope you enjoyed this tutorial.

Leave a Comment