Running templstring_demo.js

➕︎ Aa ➖︎ |Dark 1Dark 2Light|HackFira Code|Back to  PT Mono
// CPCS-223 Analysis and Design of Algorithms
// Language demo - Template/Literal Strings
// 2022, Dr. Muhammad Al-Hashimi


// to output formatted or labelled values, we normally concatenate 
// a carefully arranged comma-separated list of strings and variables

var a = 10,  myname = "Ali";
document.write( "<p>Value of a: ", a, "<p>" );

// alternately, use ` (back tick) to specify an output string instead of " or '
// enclose var name in ${ ... } inside the string to print its value

document.write( `<p>Value of a: ${a}</p>` );   // ${a} prints 10


// works for expressions
document.write( `<p>Length of string: ${myname.length}</p>` );  

// no need for crazy output line construction, 
// vars should stand out with good syntax highlighting
document.write( `<p>${myname} is his name (age ${a})</p>` ); 
// instead of this
document.write( "<p>", myname, " is his name (age ", a,")</p>" );

// template strings are available in Java, PHP, Python and most modern languages