Template literals:
ES6 introduced many cool things among which one is ‘Template literals’
This is a new way of representing strings.
Normally we use either “(double quotes) or ‘(single quote) to represent a string in JavaScript.
For example:
var name=”literal”;
Or
var name=’literal’;
But from ES6 there is a new way of doing it. We can use `(back tick) symbol which is present left to key ‘1’ in keyboard.
Ie.,
var name = `literal`;
Well when we already have “(double quotes) or ‘(single quote), what extra does `(back tick) do?
Template literals shines well when we have some concatenation of strings or when creating multi-line strings.
Look at below to understand the power of Template literals. Let's take an example where we need to form a string where you are forming a string based on a button clicked. For example - “You clicked on login button”.
Old way:
var buttonName = ‘login’; var message = “You clicked on “+buttonName+” button”;
Using template literals
var buttonName = ‘login’; var message = `You clicked on ${buttonName} button;
Simple and much readable. Isn't it?
Well let's take another one. How we used to create multi-line strings in javascript
var multiLineString = ‘First Line \n Second Line \n Third Line \n Fourth Line’;
The above turns weird and unreadable if we have many lines.
With Template literals, it's as simple as
var multiLineString = `First Line
Second Line
Third Line
Fourth Line`;
Readable and simple right? Let me know your thoughts on it.
Happy coding :)
Happy coding :)
Comments
Post a Comment