DEV Community

Syafiq Rizky Fauzi
Syafiq Rizky Fauzi

Posted on

Template Literals || ES6

Image description

Bismillah,

Hello all friends, back again with me Syafiq. Here I want to write down what I have learned about EcmaScript 6. I want to document my learning results in this platform


In this article I want to talk about something new again in ES6, namely something called Template Literals. Let's discuss them one by one.


What is Template Literals ?

So before there was a literal template in javascript developers found it difficult to combine a string and a string or commonly called string concatination using the primitive way, namely using the (+) sign, take a look at the example below:

// Prior to ES6 string concatenation in Js using operator (+)
// example
const user = {
    firstName: "Syafiq",
    lastName: " Rizky",
    age: 18
}

console.log("Name : " + user.firstName + "" + user.lastName + ", Age : " + user.age);

Enter fullscreen mode Exit fullscreen mode

See how complicated it is to write that way?

Indeed, if it is only a little value, it is easy for us to write it, but if it is long then it will make us complicated ourselves as developers. So in ES6 came a simple but powerful way to overcome this, namely with a function called template literals.

Maybe you ask what is template literals?

Template literals is a new function in ES6 where we can insert an expression into a string. Let's compare how fast and effective it is when we write code using template literals or primitive ways.

Let's see the difference in the code below

// Prior to ES6 string concatenation in Js using operator (+)
// example
const user = {
    firstName: "Syafiq",
    lastName: " Rizky Fauzi",
    age: 18
}

console.log("Name : " + user.firstName + "" + user.lastName + ", age : " + user.age);

// template Literal || ES6
// Using backtick(``) to shorten string concatenation
const userNew = {
    firstName: "Syafiq",
    lastName: " Rizky Fauzi",
    age: 18
}

console.log(`Name : ${userNew.firstName} ${userNew.lastName}, age ${userNew.age}`);


Enter fullscreen mode Exit fullscreen mode

Now, there is a very big difference between string concatination using the primitive method and the modern method. When we use the modern method, it looks cleaner code and easier to read, whereas if we use the primitive method it is quite difficult to read.


Then what should I use in my coding?

For that I give you the choice to choose the primitive or modern way, it's up to you. But my suggestion is to use template literals because in addition to making our code cleaner, it certainly saves writing code to be shorter but denser.


Hope it helps!

Like this post ?

  • You can follow me, like and share this article
  • You can also follow my github account : Syafiq's github

Thank for reading !

Top comments (1)

Collapse
 
ferdiansyah0611 profile image
Ferdiansyah

👏