Why is console.log() considered better than alert()?
I've always been told that when debugging an application, JavaScript's console.log()
method is preferred over simply using an alert()
method. Why is this? Is there a good example someone can point me to where console.log()
is obviously the better choice?
-
alert()
is blocking -
alert()
cannot be easily suppressed in non-debug environment -
console
typically formats your objects nicely and allows to traverse them - logging statements often have an interactive pointer to code which issued logging statement
- you cannot look at more than one
alert()
message at a time -
console
s can have different logging levels with intuitive formatting
Try this:
var data = {a: 'foo', b: 'bar'};
console.log(data);
alert(data);
You'll see that console.log
shows you the object, while alert
gives you [object Object]
, which isn't useful. This is true also of, e.g. elements:
alert(document.body); // [object HTMLBodyElement] (exact result depends on your browser)
Both are just a way to get information about what's happening at the time in your JS. I used to use alert() all the time but migrated to console.log() for a few reasons. (Side note: console offers more than just log(), take a look at what else it can do).
I think the main benefits of console.log() are:
- it does not halt processes like alert does
- you can see what line of what script threw the log entry without putting the line into your message
- if you have more than one thing you're debugging it can get real annoying to keep hitting 'ok' on your alert boxes
- you can log objects and get lots of good info (thanks for the reminder, other answerers)
In the end it boils down to how you prefer to debug.
One thing to be aware of. Not all browsers SUPPORT console.log() and will have a problem if you leave your console.log() calls in your code. Provide a console stub if console is not available to get around that problem.