String Substitutions In Console Strings
A little known feature of console.log and console.info is that it supports substitutions in strings and even provides some automatic formatting. For example:
function logName(name) { console.log('Hello, %s!', name) } logName('Phil'); // Hello, Phil! logName('Bob'); // Hello, Bob!
Which helps with debugging, but template strings support similar variable replacements and are well supported across all modern JS environments. Though it can be used to print objects which is useful for showing objects when you can't immediately inspect them. For example to log the contents of class including all its properties (and by extension methods):
class Car { constructor(name, hp) { this.name = name; this.hp = hp; } toString() { return `${this.name} (${this.hp})`; } } const miata = new Car('miata', 155); console.log(miata); // Car { name: 'miata', hp: 155 } console.log(Car); // [Function: Car] console.log('%o', Car); // { [Function: Car] // [length]: 2, // [prototype]: // Car { // [constructor]: [Circular], // [toString]: { [Function: toString] [length]: 0, [name]: 'toString' } }, // [name]: 'Car' }
There are a few other uses like outputing a number only as an integer and so on that you can read about here.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2019/consoleStringSubstitute.js











