DEV Community

Cover image for πŸ’¬ Create well-formatted console.log() messages using string substitution
Iain Freestone
Iain Freestone

Posted on • Edited on • Originally published at iainfreestone.com

πŸ’¬ Create well-formatted console.log() messages using string substitution

Use string substitutions tokens in your console.log() calls to create well-formatted messages.

Each substitute string (%o - object, %s - string, %d - integer, %f - floating point value ) in the message will pull in the next argument of the console.log(msg,arg1,arg2).

For example, the following example will pull in the String "Iain", followed by the String "Freestone" and finally the integer 39

console.log("User %s %s is %d years old.","Iain","Freestone",39)

Outputing - "User Iain Freestone is 39 years old."

let users = [
  {
    firstname: "Joe",
    lastname: "Bloggs",
    age: 45
  },
  {
    firstname: "Jane",
    lastname: "Doe",
    age: 34
  }
];

users.map(user =>
  console.log(
    "User %s %s is %d years old.",
    user.firstname,
    user.lastname,
    user.age
  )
);

// User Joe Bloggs is 45 years old.
// User Jane Doe is 34 years old.
Enter fullscreen mode Exit fullscreen mode

If you enjoyed this little snippet you can follow me on Twitter where I regularly post bite size tips relating to HTML, CSS and JavaScript.

Top comments (0)