06.07.2017 Views

Mastering JavaScript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

ECMAScript 6<br />

The final variation of the template strings is called tagged template string. The idea<br />

is to modify the template string using a function. Consider the following example:<br />

function emmy(key, ...values){<br />

console.log(key);<br />

console.log(values);<br />

}<br />

let category="Best Movie";<br />

let movie="Adventures in ES6";<br />

emmy`And the award for ${category} goes to ${movie}`;<br />

//["And the award for "," goes to ",""]<br />

//["Best Movie","Adventures in ES6"]<br />

The strangest part is when we call the emmy function with the template literal. It's not<br />

a traditional function call syntax. We are not writing emmy(); we are just tagging the<br />

literal with the function. When this function is called, the first argument is an array<br />

of all the plain strings (the string between interpolated expressions). The second<br />

argument is the array where all the interpolated expressions are evaluated and<br />

stored.<br />

Now what this means is that the tag function can actually change the resulting<br />

template tag:<br />

function priceFilter(s, ...v){<br />

//Bump up discount<br />

return s[0]+ (v[0] + 5);<br />

}<br />

let default_discount = 20;<br />

let greeting = priceFilter `Your purchase has a discount of<br />

${default_discount} percent`;<br />

console.log(greeting); //Your purchase has a discount of 25<br />

As you can see, we modified the value of the discount in the tag function and<br />

returned the modified values.<br />

Maps and Sets<br />

ES6 introduces four new data structures: Map, WeakMap, Set, and WeakSet.<br />

We discussed earlier that objects are the usual way of creating key-value pairs in<br />

<strong>JavaScript</strong>. The disadvantage of objects is that you cannot use non-string values as<br />

keys. The following snippets demonstrate how Maps are created in ES6:<br />

[ 172 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!