ECMAScript Template Literal
ECMAScript 6
Foreword: In this tutorial, I explain the meaning of template literal and its use.
By: Chrysanthus Date Published: 15 Jul 2016
Introduction
Pre-Knowledge
This series is part of the volume, ECMAScript Course. At the bottom of this page you will find links to the different series you should have read before coming here, to better understand this one.
Template Literal
A template literal is a string in back-ticks instead of double or single quotes.
An example of a template literal is,
`I like what I am seeing`
It can be assigned to a variable (identifier). Try the following code:
str = `I like what I am seeing.`;
alert(str);
Interpolation
Interpolation is when an expression within the back-ticks is replaced by its result and when an escaped sequence within the back-ticks has its effect.
Read and try the following code where two expressions are replaced by their results; the escaped sequence \n also has its effect:
a = 5;
b = 10;
str = `Fifteen is ${a + b} and\nnot ${2 * a + b}.`;
alert(str);
The output is:
Fifteen is 15 and
not 20
Well, you do not type the expression within the back-ticks ordinarily. You have to place the expression within curly braces and precede that with $ (even if the expression is just a single variable).
The second line in the output means \n had its effect.
Escaped Sequences or Escaped Characters are special characters. A character here actually consists of two characters with the first one being the backslash. Common escaped sequences and their meanings are:
Sequence Code Unit Value Unicode Character Name Symbol
\b 0x0008 BACKSPACE <BS>
\t 0x0009 CHARACTER TABULATION <HT>
\n 0x000A LINE FEED (LF) <LF>
\v 0x000B LINE TABULATION <VT>
\f 0x000C FORM FEED (FF) <FF>
\r 0x000D CARRIAGE RETURN (CR) <CR>
\" 0x0022 QUOTATION MARK "
\' 0x0027 APOSTROPHE '
\\ 0x005C REVERSE SOLIDUS \
Multi-Line String
Within back-ticks, any line developed without \n is maintained (spaces are also maintained). Read and try the following code:
a = 5;
b = 10;
str = `Fifteen is ${a + b} and
not ${2 * a + b}.
Just a third line`;
alert(str);
The output is:
Fifteen is 15 and
not 20
Just a third line.
That is it for this tutorial.
Chrys
Related Links
ECMAScript BasicsECMAScript Operators
Expressions in ECMAScript
Statements in ECMAScript
Custom Objects in ECMAScript
Functions in ECMAScript
ECMAScript Date Object
The ECMAScript String Object
ECMAScript String Regular Expressions
ECMAScript Template Literal
The ECMAScript Array
ECMAScript Sets and Maps
ECMAScript Number
Scopes in ECMAScript
Mastering the ECMAScript (JavaScript) eval Function
Sending Email with ECMAScript
ECMAScript Insecurities and Prevention
Advanced Course
Advanced ECMAScript Regular Expressions
Promise in ECMAScript 2015
Generator in ECMAScript 2015
ECMAScript Module
More Related Links
Node Mailsend
EMySQL API
Node.js Web Development Course
Major in Website Design
Low Level Programming - Writing ECMAScript Module
ECMAScript Course