I am writing a plugin. For that I will log a few things, say warnings, necc things, etc. To log them I will use console, but there can be an error if some browser doesn’t support console. To handle this error, I am thinking of using this code:
if (typeof console == 'undefined') console = {};
if (typeof console.log == 'undefined') console.log = function() {};
if (typeof console.debug == 'undefined') console.debug = function() {};
if (typeof console.info == 'undefined') console.info = function() {};
if (typeof console.warn == 'undefined') console.warn = function() {};
if (typeof console.error == 'undefined') console.error = function() {};
Will this work right or is there a better option?
You’re approaching it right. You could however shorten it a bit:
This allows you to use
console.log/console.debug etcwithout first checking if a console object is defined. I recommend to always include this snippet if you are logging since it is easy to forget to remove and it will break your site if no console is present.