<!doctype html>
<head>
<title>JavaScript Template Literals</title>
</head>
<body>
<div id="result_one"></div>
<div id="result_two"></div>
<div id="result_three"></div>
<script>
/* Example 1 - Simple Template Literal Expression */
var a = 7;
var b = 20;
var result = "The sum is: "+ (a+b) + " and the difference is: " + (a-b);
document.getElementById('result_one').innerHTML = result;
/* Example 2 - Nested Template */
var isCollapsed = false;
function isLargeScreen() {
// change this to false and see the output
return false;
}
var myclass = `header ${ isLargeScreen() ? '' :
`icon-${isCollapsed ? 'expander' : 'collapser'}` }`;
// adding string value to HTML tag
document.getElementById('result_two').innerHTML = myclass;
/* Example 3 */
var car = "BMW 3 Series";
var type = "Sedan";
function myTag(strings, carExp, typeExp) {
var str0 = strings[1]; // " is an "
// There is technically a string before and after
// the first and final expression (in our example),
// but it is empty (""), so disregard.
// strings[0] and strings[2];
var type;
if (typeExp == 'sedan'){
type = 'Luxury car';
} else {
type = 'economic car';
}
// We can even return a string built using a template literal
return `${carExp}${str0}${type}`;
}
var result3 = myTag `${ car } is an ${ type }`
document.getElementById('result_three').innerHTML = result3;
</script>
</body>
</html>