Running templstring_demo.js

➕︎ Aa ➖︎ |Dark 1Dark 2Light|HackFira Code|Back to  PT Mono
// CPCS-324 Algorithms and Data Structures 2
// Language demo - Template/Literal Strings
// 2020, Dr. Muhammad Al-Hashimi


// to output formatted or labelled values, we normally
// concatenate labels/markup strings with variable names

// or output a carefully arranged comma-separated list of
// strings and vars (see lines 33-34) 

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

// or 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>(line 18) Value of a: ${a}</p>` );   // ${a} prints 10

// works for expressions
var verts = [ 
   {label: "a", visit: true, adjacent: null}, 
   {label: "b", visit: false, adjacent: null} 
   ];
document.write( `<p>Length of array: ${verts.length}</p>` );  

// no need for crazy output line construction, 
// vars should stand out with good syntax highlighting
var i = 1, v = verts[i];
document.write( `VERTEX: ${i} {${v.label}} - VISIT: ${v.visit} - ADJACENCY: ${v.adjacent} <br>` ); 

// instead of this
document.write( "VERTEX: ", i, " {", v.label, "} - VISIT: ", v.visit, 
			" - ADJACENCY: ", v.adjacent, "<br>" );

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