Use Template Literals in ES6

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet

ECMAscript 6 lets us use string templates to gain a lot more control over strings in JavaScript.

Alan Plum
Alan Plum
~ 5 years ago

Probably worth mentioning that a template handler doesn't have to return a string. It can return any JavaScript value. So you can use template handlers to implement custom DSLs to describe arbitrary structures. At ArangoDB we use a template handler for the query language to make it easier to add bound parameters to a query: https://github.com/arangodb/arangojs/blob/master/src/aql-query.js

Gene
Gene
~ 5 years ago

Not a criticism of the lesson but a comment on the code function tag(strings, ...values){ The code that produces is hard to read maintain. The template syntax is great referring to variables by name. Nice and readable. But then using the tag function to manipulate the strings where positional arguments are inferred or hidden behind the runtime output leads to maintainability errors. I wonder if there is a better example of using the tag type syntax.

Alberto Díaz
Alberto Díaz
~ 5 years ago

I got this error, any idea?

function tag(strings, ...values){ ^^^

SyntaxError: Unexpected token ... at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:373:25) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10) at startup (node.js:139:18) at node.js:968:3

ecs ux
ecs ux
~ 3 years ago

Why do we need spread operator on values but not on strings?

Eleni Lixourioti
Eleni Lixourioti
~ 3 years ago

Why do we need spread operator on values but not on strings?

It's not strictly needed. You could have written the function also like this (which imo is more readable):

function tag(strings, dateValue, stateValue){
    stateValue = dateValue < 20 ? "awake" : "sleepy"
    
    return `${strings[0]}${dateValue}${strings[1]}${stateValue}`
}

it's just a way of grouping all the subsequent arguments into an array.

Tech
Tech
~ 3 years ago

How does the function know which are values & which are strings?