Before ES6, we use single quotes ('
) or double quotes ("
) to wrap a string literally. And the strings have very limited functionality.
In ES6, we can create a template literal by wrapping text in backticks (
````) Example:
let simple = `This is a template literal`;
Here are some key features of template literals:
Multiline Strings:
With template literals, you can create multiline strings without the need for escape characters or concatenation.
const multiline = `
This is
a multiline
string.` ;
Variable Interpolation:
We can simply include the variable or expression within ${}
const name = "Javascript";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, Alice!
Tagged templates:
Tagged template is written like a function definition. However, you do not pass parentheses ()
 when calling the literal.
const name = 'JS';
const greet = true;
function tag(strings, nameValue) {
let str0 = strings[0]; // Hello
let str1 = strings[1]; // , How are you?
if(greet) {
return `${str0}${nameValue}${str1}`;
}
}
// passing argument name
const result = tag`Hello ${name}, How are you?`;
console.log(result);
Top comments (0)