Deutsche Startseite · English Homepage

STRAVID - Building software collectively.

Improve your Javascript console.log friendship

In case you wonder what the hell console.log is read my earlier post Stop the Javascript alert() madness.

Many developers use the console.log in one particular way to log information, they piece together the message they want to log. Mostly this looks somehow similar to the following example.

var playerCount = 11,
    userName = 'David';

// magic stuff

console.log('Game statistics: ' + playerCount + ' players online. Logged in as: ' + userName);
// output: Game statistics: 11 players online. Logged in as: David

This style is perfectly O.K., but not the best we can get because all these + and ' make it hard to quickly change the message without breaking it. And in my opinion this style is also confusing and ugly.

In order to make it more convenient we can use string substitution patterns in the console.log method. Developers familiar with printf know what I’m talking about, but let me explain it anyway for the Javascript only folks.

The first argument of console.log is the message we want to log. We can put placeholders into this string which will get replaced in the output by the values of the additional arguments. There are 5 types of placeholders.

console.log will replace the first placeholder in the message string with the first additional argument, the second placeholder with the second additional argument and so forth. The code example from above would look like this if we use placeholders.

var playerCount = 11,
    userName = 'David';

// magic stuff

console.log('Game statistics: %i players online. Logged in as: %s', playerCount, userName);
// output: Game statistics: 11 players online. Logged in as: David

Now we have nice looking Javascript code that is easy to modify.


You have questions, ideas or feedback? I like to hear from you and I'm looking forward to exhange thoughts. Please send an email to david@strauss.io and say “Hello”.

Random Page
Sitemap
Imprint
Privacy Policy