In JavaScript, like many languages, there are built in functions/methods to make the developer’s job easier. One that is highly useful is the alert() method. First, let me say that I do not typically use this method in production code because it tends to annoy end users (think pop-ups). With that said, it is highly useful during development to see how your code is functioning. So, let’s dive in and take a look at how alert() works…
Syntax
All the alert() function does is create a pop-up window with whatever information you pass to the alert function. You can explicitly put content into the alert function or alert the value of a variable in the function. Here is the basic syntax…
[code lang=”js”]
// alert() function hello world example
alert(‘Hello, World!’);
[/code]
The aforementioned code yields the following results (in FireFox)…
Usage
So, as you can see, you can type text directly into the alert function and have it display that text in a message window. You can also do the same with variables…
[code lang=”js”]
// Variables section
// Declare variable to utilize in alert function example
var helloWorld = "Hello, World!";
// Output section
// Use alert function to display value of variable
alert(helloWorld);
[/code]
The code above will return the same results as the earlier screenshot. The difference is that this time, we are alerting a variable and not the text directly. This allows us to see what values are in the variables.
Here is an example where this might be useful in a development environment…
Imagine you have a loop that is changing the value of a variable, then you are outputting that variable to the screen. When you run your code, the out put you are expecting is not what displays. You can use an alert to watch your variable value change while it is looping.
[code lang=”js”]
// Processing and output section
// Use alert function to display value of variable within a loop
for(firstNum = 0;firstNum < 3; firstNum++){
alert(firstNum);
}
[/code]
The aforementioned code should loop three times and output the value of the firstNum variable. Since it runs three times, it will alert three times. The first alert displays ‘0’ because the value of the firstNum variable is ‘0’. We are adding one (1) to it each loop. So the second alert displays ‘1’. The third time through, it displays ‘2’.
So the alert function is a very useful function to be able to watch your variables and output the data within them so you can see how your code is functioning. Just a quick side note on using alerts in loops like I demonstrated…do not use it on large loops, unless you like clicking a lot! There are better ways to output that data (hint: console).
Happy Coding!
Clay Hess