4
Jan 28 '12
you can use document.write(myString);, which is generally frowned upon for real applications due to its being terribly inefficient.
you can use alert(myString); which is generally frowned upon for real applications because it blocks and because it interrupts the user in a jarring way
you can use console.log(myObject); which is great in conjunction with firebug for developing, but otherwise will cause an error
But these are only for simple string output. You could create a printf-alike in JS pretty simply, but a word of warning; JS is not a strongly typed language, by asking for printf it seems like maybe your attitude is still that of a strongly typed language.
Finally, what would be the point of printf in JS? You can just concatenate into a string? The only time I've used/wanted/needed anything similar is in NodeJS when writing prepared SQL statements - and in that case the library has support for that, eg
sql.query('SELECT * FROM Foo WHERE Name=? AND Age BETWEEN ? AND ?', ['John', 17, 39], myCallback);1
u/x-skeww Jan 28 '12
printfis short for "print formatted" (the 's' insprintfstands for string, you "print" into a string). It does a bit more than blind concatenation. E.g. you can print a number as hex value, you can specify the amount of decimal places, you can print leading zeros, and things like that.1
Jan 28 '12
yeah I know, but I mean because of the loose typing, you can concat decimals with strings, eg:
var formatted = "Your total is $"+(82.324324).toFixed(2);and it won't complain, unlike in C where AFAIK concatting a string with a decimal was a PITA and so printf was a nice way around that. In JS - just concat all the variables of various types and you'll be fine. OK so you'll have to format them yourself but that's not hard.
edit: ok, toFixed returns a string, but you get what I mean
var formatted = "Your total is $"+(Math.round(82.324324*100)/100);works.
2
u/x-skeww Jan 28 '12
var formatted = sprintf('Your total is $%.2f', 82.324324);It's a lot easier to read. Especially if there is more than one value and if there are spaces next to your values.
E.g.:
var formatted = 'Hey, ' + firstName + ' ' + lastName + ' your total is $' + (total).toFixed(2) + '.'; var formatted = sprintf('Hey, %s %s your total is $%.2f.', firstName, lastName, total);The first one is kinda error prone to type. Often Komodo will give me a squiggly red underline and I have to reread it a few times until I finally find the missing '+'.
A quick and dirty Handlebars example (untested):
Handlebars.registerHelper('dollars', function(money) { return '$' + (+money).toFixed(2); }); [...] var template = Handlebars.compile('Hey, {{firstName}} {{lastName}} your total is {{dollars total}}'; [...] var formatted = template({ firstName: 'Peter', lastName: 'Parker', total: 82.324324 });That dollars helper function can be reused application wide. It could be also something more generic, which handles all kinds of currencies and also different kinds of number formatting.
If I understand ECMA6 quasi literals correctly, something like that could work at some point in the future (untested, naturally):
var template = function (ctx) { return `Hey, ${ctx.firstName} ${ctx.lastName} your total is ${(total).toFixed(2)}.`; //yes, backticks } var formatted = template({ firstName: 'Peter', lastName: 'Parker', total: 82.324324 });2
Jan 28 '12
var formatted = 'Hey, ' + firstName + ' ' + lastName + ' your total is $' + (total).toFixed(2) + '.'; var formatted = sprintf('Hey, %s %s your total is $%.2f.', firstName, lastName, total);I really don't like the latter. what happens when things get more complicated and you have 5 or 6 variables? You then have to count the %s's and the vars. I find it much easier to write, edit, read and debug the former. Yes honestly.
Just skim over the two lines quickly.
The first says "Hey firstname lastname your total is $total tofixed 2".
The second says "Hey s s your total is $ 2f firstname lastname total"
I honestly can't see how the latter is preferable. It offers a convenient method for formatting, yes, but I find it much less readable.
The former is more prone to syntax errors - which happen once, and then are fixed. You read code more than you write it. Therefore optimise for performance, then readability, then writeability.
4
u/x-skeww Jan 28 '12 edited Jan 28 '12
The base library was made for doing stuff in a browser.
printf (and friends) are more for CLI things.
That's the best explanation I can offer.
https://github.com/epeli/underscore.string
http://www.diveintojavascript.com/projects/javascript-sprintf
Edit: If you want to use it for outputting markup, use templates instead (Mustache or Handlebars).
1
Jan 28 '12
There is a library on github which implements something like it: https://github.com/samsonjs/format
1
1
u/joshuag Jan 28 '12 edited Jan 28 '12
Here's a quick and dirty sprintf implementation that I wrote.
You can have it.
String.prototype.sprintf = function(){
output = this.toString();
for(var i=0;i < arguments.length;i++){
asNum = parseFloat(arguments[i])
if(asNum || asNum == 0){
suffix = (asNum > 1 || asNum == 0)?"s":""
output = output.replace(/%s {1}(\w+)\(s\){1}/, "%s $1" + suffix)
}
output = output.replace("%s", arguments[i])
}
return output;
}I'm not sure of all the implementation details of the original sprintf. I just needed a quick way to print into a string quickly. I also added a shortcut that will detect numeric arguments and optionally pluralize words for you.
so:
"I have %s item(s) but only %s thing(s)".sprintf(3, 1)results in the string:
"I have 3 items but only 1 thing"EDIT: I just saw this (http://www.diveintojavascript.com/projects/javascript-sprintf) further down the page. It's a much better, not-so-dirty implementation of sprintf. Use that.
1
u/bart2019 Jan 28 '12
"%s" is only the simplest use for (s)printf, and the one the least missed.
A more useful use for (s)printf in other languages is to format numbers with "%f", for example "%.3f" to get exactly 3 decimals.
But Javascript has a nice alternative: Number.toFixed(decimals):
var n = 1.123456789; alert(n.toFixed(3)); // 1.1231
u/joshuag Jan 29 '12
I'm not sure of all the implementation details of the original sprintf. I just needed a quick way to print into a string quickly.
I understand and appreciate the urge to correct someone on the internet, though, so thank you for the elucidation.
1
u/stiggz Jan 28 '12
every language prints lines differently.. although syntax may change, design patterns stay the same in many languages. Don't be thrown off by new syntax, just keep a handy reference of common functions, keywords, and operators while you're reading code to familiarize yourself with the langauge.
7
u/greut Jan 28 '12
Maybe because JavaScript was designed to be run into an environment without any stdout/stderr - where should it print it by default? meh.
If you wanna talk about the f part of your question, they never had to think about it maybe.