Javascript

console.log vs alert

If you’re debugging an application, then you want some feedback to know what’s going on inside the program. You can manually step through every function in your code. Or you can output a message to the screen or to the console. But which one is best, or do they both have their merrits?

Alert() is old school

Modern browsers have a superb set of debugging tools and options, but before this was not always the case. So in order to see what whas happening, you had to get a message to the outside. Alert() makes a pop-up window and writes a custom message in it. Ideal for checking the contents of variables and so on.

What are some of the drawbacks of Alert()?

  • alert() blocks your code until you press ‘OK’. Thus slowing the debugging process.
  • You cannot see more than one alert() message at a time. This forces you to use your memory. And multiple runthroughs to be sure if you’ve forgotten something.
  • alert() outputs a string, but it has only limited formating. For example: If you feed it an object it will just output [object] instead of the contents of that object

Alert [object]

  • You have the potential risk of showing an alert() to an end user.

Console.log() is the way

It has the same purpose as alert() but it does it more elegantly. It’s not blocking, you can view multiple logs at one time and you can feed it any object you like.

It’s purely designed for developers and thus is the prefered way to do your debugging.

So, alert is bad and console.log is good?

I wish it was so simple. In most cases I would advise to use console.log(). But in some cases alert() is the way to go.

For example:

var anArray = new Array(20);
anArray[4] = "red";
anArray[10] = 30;
console.log(anArray);
alert(anArray);

console.log will format this to show only the filled array slots. and you won’t know how large the array is. alert() on the other hand will show every entry separated with a comma.

alert console.log array

It could save you some time knowing about it. While it’s easier to see which positions are filled in console.log, you can’t see the lenght of the array at the same time. console.log(anArray.lenght); ┬áBut if you don’t type the previous statement, then it’s easy to overlook.

alert() can offcourse be used to alert() the end user of something. But then this is not debugging, but rather user experience. (a bad user experience according to me.)

Leave a Reply

Your email address will not be published. Required fields are marked *