Javascript ES6 Template Literals

Hello immersers, today I want to briefly cover Javascript’s Template Literals something the previous version ES5 was severely lacking when compared to other interpreted languages, PHP, Ruby and Python. But we can hardly compare Javascript with those, Javascript is fun, wild and deserves its own realm. Still though, template literals introduced in ES6 makes for cleaner code, readability, just easier on the eyes.

Multiline Strings

Multiline strings weren’t that too much of a headache, unless they were extremely long or part of a gigantic program. In ES5, the old school way of constructing multiline strings would be done by the following:


var name = 'Mark';

var greeting = 'Hello ' + name;

console.log(greeting); // Output: Hello Mark

Alright, that doesn’t look too bad. In fact tons of legacy javascript programs still use this way of concatenation strings.

Multiline, the old school way, ES5


var name = 'Mark';

var greeting = "Hello \" + 
 name;

console.log(greeting); // Outputs: Hello Mark

The above code does the exact same thing, outputs the variable string in one line however when initially declared – in the event where long strings may need to be broken up into multiple lines, we use the backslash to achieve this. Even more, we also concatenate our “name” variable within the same variable.

Sounds good and gravy, but how do we break the output into multiple lines and concatenate a variable? Well the ES5 way provides a workaround for this. We use the “\n” keyword to break up our lines.


var name = 'Mark';

var greeting = "Hello \n" +
 name;

console.log(greeting); 

// Outputs:
// Hello
// Mark

Another way, rarely used method of creating multiline strings involves creating an array and then applying the join function immediately afterward to achieve the desired result.


var name = 'Mark';

var greeting = [
    "Hello ",
    name
].join("\n");

console.log(greeting);

// Outputs:
// Hello
// Mark

Multiline Strings the ES6 way

Now that we’ve got a good handle on the ES5 way of creating multiline strings – now we can dive into ES6 features. It’s helpful to understand and learn both methods, out there in the wild.

Now in one fell swoop, we simply use backticks “ instead of double or single quotes ‘ and “”. We top it off by using “${}” instead of using a bunch of “+” to concatenation strings and variable substitutions.


var name = 'Mark';

var greeting = `Hello
${name}`;

console.log(greeting);

// Outputs:
// Hello 
// Mark

Something to note, you will encounter both ES5 and ES6 implementations out in the wild as already mentioned. So it’s important to know both. In future posts, I will be covering yet another powerful feature using template literals – something I haven’t really used in my own code base are the usage of tags. Stay tuned for that. Keep immersing!

Leave a Reply

Your email address will not be published. Required fields are marked *