Shorter JavaScript console.log function

08 August, 2014 by Tom Elliott

If you’ve ever found yourself annoyed at frequently having to write ‘console.log’ in JavaScript when debugging code, then the below console.log shorting function could be for you:

function cl(logstring) {
  if (navigator.appVersion.indexOf("MSIE 8") == -1) {
    return console.log(logstring);
  }
}

This can then be called by passing your variable, parameter or other string to the shortened ‘cl’ function as below:

cl(variable);

As console.log isn’t supported in Internet Explorer 8, basic browser detection will also prevent the function from being triggered in this browser. This means you don’t have to remove console.log from your JavaScript which would have otherwise thrown errors in IE 8.

You could of course write a snippet in your code editor instead to also display ‘console.log’ using a shortcode. For example, I have ‘cl + TAB’ setup in Sublime Text. This means you would still have to go through and remove console.log from your JavaScript to satisfy older browsers, unless you’re using a minifier which will automatically remove all console.log lines from your JS.

The console.log shortening function has been tested on all major browsers: Chrome, IE 9+, FireFox and Safari.

Note: This function will not return the desired line number and instead returns the line number of wherever the function is placed.



One Comment

  • Alex says:

    This function only takes one argument and calls console.log with it, but console.log can be called with a variable number of arguments that are being printed to the console.

    This version would be better:

    function cl() {
    if (navigator.appVersion.indexOf(“MSIE 8”) == -1) {
    return console.log(arguments);
    }
    }

  • Leave a Reply

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

    css.php