ES6 Tutorial - Template strings
   Jan. 2nd,2018
   Ismail Nassor Mbarack

Template string is one of the coolest features added in ES6.Remember the hustles we used to go through when we wanted to append a certain HTML content into the DOM or when we wanted to concatenate a certain variable to the HTML markup in JavaScript?If you aren't still getting what it is let me show you with these few examples.

//the ES5 way
//The backslashes we used to escape the return
var myHtml = '<div>\
        <div>Some text</div>\
    </div>';


//The plus sign we used to concatenate the variables in the html content
var user = "Ismail Mbarack";
var myOtherHtml ='<div>\
        <div>Welcome '+user+'</div> \
    </div>';

console.log(myHtml);
console.log("======$$$$=======");
console.log(myOtherHtml);

 

That's how we used to do, remember now?It worked and still does work but trust me, it was a lot of pain especially when you had a bunch of HTML that you wanted to insert into the DOM, plus it wasn't tidy at all.With ES6 things got waaaaay better.With the use template string, we can be able to transform the above code as the way it is below.

//the ES5 way
//Just use the backticks and remove all the ugly backslashes we used before
let myHtml = `<div>
        <div>Some text</div>
    </div>`;


//Use ${variableName} to concatenate the variables in the HTML content
let user = "Ismail Mbarack";
let myOtherHtml =`<div>
        <div>Welcome ${user}/div>
    </div>`;

console.log(myHtml);
console.log("======$$$$=======");
console.log(myOtherHtml);

 

See how our code got cleaner?And if you're going to learn some JavaScript Frameworks like Vue JS, you gonna use these template strings a looot.