This is what I do. You have to define a variable that indicates you are in development, and not in production. Output that to your HTML with your pre processor language (PHP.., etc). Some old IE browsers don't have the console object.
You have options when figuring out how to define __DEV__ You can check the host-name with JavaScript and define __DEV__ if it doesn't equal your production domain name, or you could output the JavaScript code on the server side after checking some environment variable.
if(typeof window.console === 'undefined') {
window.console = {
log: function() {}
// etc, define all the methods for which you will call
// while developing.. warn, debug..
}
}
var CONSOLE = window.console.log; // get a reference to the function
window.console.log = function() {
if(typeof window.__DEV__ != 'undefined') {
return CONSOLE.apply(this, arguments);
}
}
This is more efficient then writing something to remove all of the console.* calls in your code. You don't want to have to get used to a new calling construct such as logger.log because that would just waste time. This way you can still use your normal logging conventions, but it won't output in your production environment.
If __DEV__ is not found, then it won't log. By default it won't log. You need to define __DEV__ at the top of your HTML document.
JSFiddle Example