Last Updated: February 25, 2016
·
8.23K
· akhyar

Shorten up console.log() in JavaScript

Debugging in JavaScript can be irritating sometimes, repeatedly typing console.log() is an annoyance. I always make a shorter shortcut for it to save my time.

function d(msg) {
    console.log(msg);
}

I'd like to make it as short as possible, so I choose a single letter function name ;)

Next time I need to debug some variable, I just need to type d(someVariable). Great, it's now prettier :p

6 Responses
Add your response

ever tried:
var d = console.log ?

over 1 year ago ·

@greelgorke Well, var d = console.log won't work, because it will trigger a TypeError:)

Personally I don't mind using console.log, since, well... I use snippets. Anyway, if you want to be a little bit more elastic and pass all arguments to aliased console.log method, you could use something like that:

window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console){
    console.log( Array.prototype.slice.call(arguments) );
  }
};
// source: https://github.com/h5bp/html5-boilerplate/blob/943968c7c9da05ac7bb3ae9d6127b7d70f2d9f2e/js/plugins.js

This piece of code may look familiar to those, who used previous versions of HTML5 Boilerplate. The method was removed from plugins.js some time ago.

over 1 year ago ·

@paprikkastudio a TypeError? interesting... in node, and ff it works as expected, in chrome and safari there is a typeerror. i think it's when not a bug, then at least bad implementation. but hey! try that:

var f = console.log.bind(console)

;)

PS: of course this version is nearly the same as the opening tip :D

over 1 year ago ·

@greelgorke Yeah, I agree in 100%, that's really, really annoying when you work in node inspector and developer tools at the same time:)

Regarding fn.bind - I don't know why I didn't think of that! That'a a lot better solution, however you have to remember that IE8 even with developer tools enabled will throw an error, since it doesn't support ES5 bind method.

That's why I prefer typing log + [TAB] in my editor and just polyfill console.log in situations it's disabled (but that's another topic, of course).

over 1 year ago ·

@paprikkastudio IE8 is a different beast. i'm all for snippeting too. <3 sublime for it

over 1 year ago ·

Bear in mind that this could prevent some JS minifiers from properly removing debugging / console statements when this option is available, as most of them will remove console.xxxx calls only.

over 1 year ago ·