Template strings & interpolation

November 22, 2016, 8:56 pm Categories:

Categories

Remember how, in those pre-ES6/TypeScript days, you'd use syntax like the following to mix string values and variables?

var name     = "Hamlet",
    sentence = "To be or not to be?",
    elem     = "The following quote: " + sentence + " \
\nis attributed to " + name;
console.log(elem);

//Outputs
The following quote: To be or not to be? 
is attributed to Hamlet

It was ugly, convoluted and often prone to errors - particularly if you missed a quotation mark or concatenation operator (the + symbol)....and wasn't that a joy to debug?

TypeScript provides a much simpler and easier syntax to accomplish the above.

Using a combination of template strings and interpolation we can mix variables, strings and, if necessary, HTML tags over a single line or multiple lines like so:

var name     = "Hamlet",
    sentence = "To be or not to be?",
    elem     = `The following quote: ${sentence} 
is attributed to ${name}`
console.log(elem);

//Outputs
The following quote: To be or not to be? 
is attributed to Hamlet

Note the use of the backtick characters (`) in constructing the template string.

The interpolation placeholders - defined by the use of the ${ } construct - encapsulate each of the pre-defined variables inside the template string. These are subsequently treated and evaluated as JavaScript expressions allowing their values to be output to the console from within the template string.

Summary

Template strings and interpolation is such a simple feature yet incredibly useful for creating strings consisting of combined data types, multiline comments and last, but definitely not least, great for debugging purposes.

We'll be covering TypeScript features in further articles and you can also find more information and examples featured in my e-book: Mastering Ionic 2.

Tags

Categories

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.

Top