Strings and Template Literals in Javascript

  • Post category:Javascript
  • Reading time:3 mins read

In this post, we will learn the basics of strings and what are Template Literals in Javascript. Template Literals is an important topic and you will most likely use it in your daily coding activities when developing a project.

Strings in Javascript

A string can be a sentence, single word, numbers, alphabets, symbols, etc. It is a primitive data type in Javascript.

let x = "javascript is fun";
let y = "2";
let z = "$";

All these are strings in the above code. So, basically, if anything is written in ” ” will be a string in Javascript. In this code, I have written 2 in ” “. So, it is also considered a string.

let first = "Traveling to USA";
let second = "next year";
let mySentence = "I will be" + " " + first + " " + second;
console.log(mySentence);
Output: I will be Traveling to USA next year

In the above code, I have used variables first and second in mySentence to make a complete sentence.

But we can do this same thing easily using the template literals.

Template Literals in Javascript

To use template literals we need to write backticks (` `) and write the sentence inside the ` `. We have to write a variable in ${ }. Let’s understand using an example.

let first = "Traveling to USA";
let second = "next year";
let mySentence = `I will be ${first} ${second}`;
console.log(mySentence);
Output: I will be Traveling to USA next year

In this example, you can see that I have written the whole sentence in ` ` and variables in ${}. I have written variables first and second in ${}.

You can see the difference between using the common way and template literals. Using template literals we don’t need to use + to concatenate two strings. We also don’t need to use  ” “ for leaving blank spaces between two words.

We can also skip lines using template literals and for that, we don’t even need to use \n for changing to a new line. See the below code.

let mySentence = `I have
changed
the
line
using
template
literals`;
console.log(mySentence);
Output:
I have
changed
the
line
using
template
literals

Template literals is an easy way to concatenate multiple strings and using multiple variables to display the values in the string.

Share this