printf() in JavaScript???

Blog
The best minds from Teradata, our partners, and customers blog about whatever takes their fancy.
Teradata Employee

Well not exactly printf(), but still pretty darn cool. I consider myself a decent JavaScript programmer with a fair amount of debugger knowledge. However, I stumbled across an interesting bit of new (to me) information last night. Maybe everybody else is already hip to this. If so then I am an uninformed idiot; well I guess this isn’t exactly the straw that broke the camel’s back on that front. Anyway…

Are you tired of writing the following?

var userName = 'Jason', color = 'pink', age = 100;
console.log("My name is " + userName + " and I am " + age + " years old. My favorite color is " + color + ". I live for JavaScript. So sad.");

Play it again Sam

var userName = 'Jason', color = 'pink', age = 100;
console.log("My name is %s and I am %d years old. My favorite color is %s. I live for JavaScript. So sad.", userName, age, color);

That is pretty awesome if you ask me and since you are reading this I am assuming that you asked me. Below is a table containing the substitution strings, which I pulled directly from the console MDN docs. This works in the Chrome debugger in addition to Firebug.

Jason, just where did you pick up this wonderful wizardry? You sure are inquisitive today. I learned about it when I attended a JavaScriptU workshop on node.js in the world’s classiest city, San Diego.

Substitution stringDescription
%oOutputs a hyperlink to a JavaScript object. Clicking the link opens an inspector.
%dOutputs an integer. Formatting is not yet supported.
%iOutputs an integer. Formatting is not yet supported.
%sOutputs a string.
%fOutputs a floating-point value. Formatting is not yet supported.

Disclaimer for trolls: Yes this could easily be hacked together. I am just bringing attention to the fact that it exists and you don't have to waste your time cutting the code yourself.