What are Template Literals and why you should use them?

What are Template Literals and why you should use them?

ยท

3 min read

Hello Folks ๐Ÿ‘‹

What's up friends, this is SnowBit here. I am a young passionate and self-taught frontend web developer and have an intention to become a successful developer.

In this article, I will be explaining a very useful topic in Javascript - Template Literals.


What are template literals?

  • In Javascript, template literals use backticks(``) to define a string instead of double ("") and single('') quotes.
  • Template literals is an ES6 feature introduced back in 2015

Mac-Print-screen-keyboard Image source: IOSHacker

Benefits

  • Quotes are allowed

When using template literals, you can use both double and single quotes inside a string.

const x = "I love \"JS\"" // without template literals

const y = `I love "JS"`

As you can see, it is too complex to escape literal quotes assigned to variable x. And it is too simple to use quotes inside a string with template literals.

awesome

FreeCodeCamp has a great explanation on "Escaping literal quotes in a string" the thing that I have done on variable "x" in the above code snippet

  • Multi-line strings

Usually, you cannot write a multi-line string with double and single quotes in Javascript. Instead, you have to use \n to break a line.

const a = 
"I
love 
JS" // โŒ

const b = "I\nlove\nJS" // โœ…

Here Comes

Template Literals

You can write multi-line flawlessly with Template Literals without any limitations.

const multiLineStr = `
I
Love
JavaScript
`
  • Variables inside a string

Usually, we all use plus(+) to concatenate a string with a variable or an expression.

const hello = (name) => {
    return "Hello " + name;
}


const favouriteFood = "Pizza"
console.log("My favourite food is " + favouriteFood)

With, template literals our tasks become a lot simpler.

const hello = (name) => {
     return `Hello ${name}`;
}

const favouriteFood = "Pizza"
console.log(`My favourite food is ${favouriteFood}`)

When passing variables in template literals, a variable must be enclosed by curly braces and preceded with a dollar symbol($).

  • Expressions in a string

With template literals, one can pass expressions in a string just like variables.

const sum = (a, b) => {
   return `Sum of ${a} and ${b} is equal to ${a+b}`
}

const PI = `Value of PI is ${Math.PI}`

Should you use template literal?

Yes. Seeing this many benefits ๐Ÿคฉ pulls me to use template literal. Let me know your thoughts about using it in the comments below, I will be glad to read your comments


Thank you for reading, have a nice day! Your appreciation is my motivation ๐Ÿ˜Š

ย