Logging variables via an ES6 tagged template
This blog post shows how you can use a tagged template to log variables more efficiently.
In order to understand it, you should be familiar with ECMAScript 6 template literals and tagged templates. For an introduction, consult chapter “Template literals and tagged templates” of “Exploring ES6”.
The problem: redundancy
If you want to log both name and value of a variable in a traditional manner, there is redundancy:
let tmp = 123;
console.log('tmp='+tmp);
// Output:
// tmp=123
Even a template literal doesn’t help:
console.log(`tmp=${tmp}`);
The solution: a tagged template
The solution is to implement a custom tag function called vars
. A template tagged with that function eliminates the redundancy:
console.log(vars`${{tmp}}`);
The object literal {tmp}
inside the substitution ${}
is an abbreviation for (a so-called “property value shorthand”):
{tmp: tmp}
Accordingly, the tag function vars
expects its substitutions to be objects:
function vars(templateStrings, ...substitutions) {
let result = templateStrings[0];
for (let [i, obj] of substitutions.entries()) {
let propKeys = Object.keys(obj);
for (let [j, propKey] of propKeys.entries()) {
if (j > 0) {
result += ', ';
}
result += propKey+'='+obj[propKey];
}
result += templateStrings[i+1];
}
return result;
}
You can put multiple variable names inside a substitution:
let foo = 123;
let bar = 'abc';
let baz = true;
console.log(vars`Variables: ${{foo, bar, baz}}`);
// Output:
// Variables: foo=123, bar=abc, baz=true
Comments
Post a Comment