đź’»ES6 tutorial: template literal in javascript

Share this post:


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`;


Enter fullscreen mode

Exit fullscreen mode

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.` ;


Enter fullscreen mode

Exit fullscreen mode



Variable Interpolation:

We can simply include the variable or expression within ${}



const name = "Javascript";
const greeting = `Hello, ${name}!`;

console.log(greeting); // Output: Hello, Alice!


Enter fullscreen mode

Exit fullscreen mode



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);


Enter fullscreen mode

Exit fullscreen mode



Source link