Should I be removing console.log from production code?

Another way of dealing with this is to 'stub' out the console object when it isn't defined so no errors are thrown in contexts that do not have the console i.e.

if (!window.console) {
  var noOp = function(){}; // no-op function
  console = {
    log: noOp,
    warn: noOp,
    error: noOp
  }
}

you get the idea... there are a lot of functions defined on the various implementations of the console, so you could stub them all or just the ones you use (e.g. if you only ever use console.log and never used console.profile, console.time etc...)

This for me is a better alternative in development than adding conditionals in front of every call, or not using them.

see also: Is it a bad idea to leave "console.log()" calls in your producton JavaScript code?


You should not add development tools to a production page.

To answer the other question: The code cannot have a negative side-effect:

  • window.console will evaluate to false if console is not defined
  • console.log("Foo") will print the message to the console when it's defined (provided that the page does not overwrite console.log by a non-function).

UglifyJS2

If you are using this minifier, you can set drop_console option:

Pass true to discard calls to console.* functions

So I would suggest to leave console.log calls as they are for a most trickiest part of the codebase.


If minification is part of your build process, you may use it to strip out debug code, as explained here with Google closure compiler: Exclude debug JavaScript code during minification

if (DEBUG) {
  console.log("Won't be logged if compiled with --define='DEBUG=false'")
}

If you compile with advanced optimizations, this code will even be identified as dead and removed entirely


Yes. console.log will throw an exception in browsers that don't have support for it (console object will not be found).