ES6: Template Literals

Marina Shafiq
Mar 19 · 2 min read
ES6 : Template Literals

A new and fast way to deal with strings is Template Literals , which we will discover in this Article - Let’s start!


How we were dealing with strings before ?

Before we used to see strings between single ‘ ’ or double “ ” quotes , as shown below :

var name = "Marina" ;
var hello = "Hello "+ name ;
console.log(hello); //Hello Marina

till now it’s good , but problem appears when you try to create a multi line template and trying to concatenate variables and expressions , and then add a quote inside string so you need to alternate between single and double quotes .. what a hustle just to generate a string !


ES6 came with a great Solution to save you , Welcome Template Literals .

What is Template literals ?

As we mentioned before , it’s a way to deal with strings and specially dynamic strings ; so you don’t need to think more about what’s the next quote to use “ single or double “ !!

How to use Template literals ?

It uses a `backticks` to write string within it , so you can write single and double quotes as much as you need without thinking to alternate between them , they will show as you write them .

var template = `Hello from "template literals" article , check previous one 'arrow functions'.` ;
console.log(template) // Hello from "template literals" article , check previous one 'arrow functions'.

Also it solved multi line templates so no need to use \n or \t with `backticks`

Thanks to Vojtech Ruzicka’s Programming Blog for GIF

And finally for variables and expressions you want to concatenate to your string instead of using + to concatenate , you will use ${variable or expression} to define a variable or expression within curly braces , for example :

Variables :

let name = "Marina" ;
let hello = ` Hello ${name} .`
console.log(hello); // Hello Marina .

Expressions :

let isWorld = true ;
let welcome = ` Hello ${ isWorld ? "World" : "me" } ! ` ;
console.log(welcome); // Hello World !

Summary

  • Template literals is a way to deal with strings .
  • Template literals uses `backticks` to write a string within .
  • Better to use with templates has multi line , concatenation of variables and expressions .

this is all what you need to know about Template literals , I hope you enjoyed and learned .

Reading is good but reading with implementation is great !

Happy learning ..

Marina Shafiq

Written by

Front End Developer ..

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade