Logger Tagged Template Literal

In his GitHub book You Don’t Know JS Kyle Simpson talks about tagged template literals. In Front End Master course he also gives an example of a useful console logger tagged template literal shown below:

// consoleLogger.js
module.exports = function (strings, ...values) {
    var str = ""
    for (let i = 0; i < strings.length; i++ ) {
        if (i > 0) {
            if (values[i-1] && typeof values[i-1] == "object") {
                if (values[i-1] instanceof Error) {
                    if (values[i-1].stack) {
                        str += values[i-1].stack
                        continue
                    }
                } else {
                    try {
                        str += JSON.stringify(values[i-1])
                        continue
                    } catch (err) {}
                }
            } 
            str += values[i-1]
        }   
        str += strings[i]
    }
    console.log(str)
    return str
}

Here is how to use the function above:

// consoleLoggerUsage.js
const consoleLogger = require("./consoleLogger")

var v = 42
var o = { a: 1, b: [2, 3, 4] }

consoleLogger `This is my value ${v} and another ${o}`

try {
    nothing()
} catch (error) {
    consoleLogger `Caught ${error}`
}

Here’s the output:

$ node consoleLoggerUsage.js 
This is my value 42 and another {"a":1,"b":[2,3,4]}
Caught ReferenceError: nothing is not defined
    at Object.<anonymous> (C:\Projects\javascript\node-sandbox\consoleLoggerUsage.js:9:5)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)  
    at internal/main/run_main_module.js:17:47

References

You Don’t Know JS

Frontend Masters course JavaScript: The Recent Parts

Share this article

Posted

in

by

Tags: