Javascript: using placeholders %s, %d... in the javascript console and in strings

Many developers use the console.log API-function to log information, concatenating the values with strings with the plus symbol '+'. This will then look like:




Whilst this style of writing is perfectly O.K., the plus + always invokes toString() as a universal member function of the respective object, and confusion increases with increasing length of the string, leading to errant breaks in the syntax.

Partly out of convenience and partly out of necessity, string placeholders or substitution patterns are supported in the log method of the console's log function. These are reminiscent of C's and C++'s sprintf, which is also available as a port  in Javascript.

console.log takes the string with the placeholders as first, arguments, and with any additional arguments being matched to the corresponding placeholder from left to right and replaced by the argument.

Five types of placeholders are available:

  • %s converts the argument to a String value
  • %d converts the argument to a double value
  • %i converts the argument to a integer value
  • %f converts the argument to a  floating point number
  • %o converts the  argument to an Object
LihatTutupKomentar