loading...
Cover image for 💬 Create well-formatted console.log() messages using string substitution

💬 Create well-formatted console.log() messages using string substitution

iainfreestone profile image Iain Freestone Updated on ・1 min read

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.

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.

Posted on by:

iainfreestone profile

Iain Freestone

@iainfreestone

A Web developer from Hampshire in the south of England.

Discussion

markdown guide