In this JavaScript lesson we are going to talk about JavaScript Template Literals, so template literal are an improvement on string concatenation that you should rarely ever combine strings with traditional concatenation. it is a new feature in JavaScript ES6
For example in here we want to concatenate two strings, you can use plus sign like this to concatenate these two strings.
1 2 3 4 5 6 |
let name = "Parwiz"; let lname = "Forogh"; let fullname = "My name is " + name + " and my lname is " + lname; console.log(fullname); |
Now in ES6 JavaScript we can use template literals to do our concatenation. you can easily use back ticks for doing this.
1 2 3 4 5 6 |
let name = "Parwiz"; let lname = "Forogh"; let fullname = `My name is ${name} and lname is ${lname}`; console.log(fullname); |
Let’s create another example, we are going to create a simple function and we want to make upper case our name, for this you can use toUpperCase() function from JavaScript.
1 2 3 4 5 6 7 8 |
function display(name) { return `${name.toUpperCase()}` } console.log(display('parwiz')); |
JavaScript Template Literals Features
As we have already mentioned that literals are feature introduced in ECMAScript 6 (ES6) that allows for more flexible string formatting. Template literals are enclosed by backticks (`) instead of single or double quotes and support placeholders, expressions and multiline strings. these are some features of JavaScript Template Literals along with commented code examples:
- String Interpolation: Template literals allow variables and expressions to be interpolated directly into a string.
1 2 |
const name = "John"; console.log(`Hello ${name}!`); // Output: Hello John! |
In this example variable name is interpolated directly into the string using the ${} syntax within the backticks.
- Multiline Strings: Template literals can span across multiple lines and it maeks it easier to create multiline strings without using concatenation.
1 2 3 4 5 6 |
const message = `This is a multiline message`; console.log(message); // Output: This is a // multiline // message |
In this example backticks allow the string to span across multiple lines without using concatenation.
- Tagged Templates: Template literals can also be tagged with a function that modifies the template literal output.
1 2 3 4 5 6 7 8 9 |
function tag(strings, ...values) { console.log(strings); // Output: [ 'The product is ', ' dollars.' ] console.log(values); // Output: [ 10 ] return `${strings[0]}${values[0] * 2}${strings[1]}`; } const product = 10; const message = tag`The product is ${product} dollars.`; console.log(message); // Output: The product is 20 dollars. |
In this example tag function is used to modify the output of the template literal by doubling the value of product variable and returning a new string.
In result we can say that JavaScript Template Literals provide a lot of flexibility and can make it easier to write and format strings in JavaScript.