DEV Community

Cover image for A lesser used feature of template litrals in Js
Arun Prakash Pandey
Arun Prakash Pandey

Posted on

A lesser used feature of template litrals in Js

TLDR: another way of calling a function

This is about one of the more advanced ES6 features called Tagged Template Literals.

-> Normal Template Literal

Normally, a template literal just substitutes values.

const name = "John";
const age = 25;

const s = `My name is ${name} and I am ${age}.`;

console.log(s);
// My name is John and I am 25.
Enter fullscreen mode Exit fullscreen mode

-> Tagged Template Literal

customFunction`My name is ${name} and I am ${age}.`
Enter fullscreen mode Exit fullscreen mode
  • Notice: The function name is written immediately before the backticks and it is without the parenthesis.
customFunction(`My name is ${name}`) // not like this
Enter fullscreen mode Exit fullscreen mode

So what?

Internally, it becomes something like:

customFunction(
    ["My name is ", " and I am ", "."], // first argument
    name,                               // second argument
    age                                 // third argument
);
Enter fullscreen mode Exit fullscreen mode
  1. The first argument contains an array of all the literal text.

    ["My name is ", " and I am ", "."]

  2. And then the remaining arguments follow.

It is basically

function customFunction(strings, ...values) {
//any custom logic that is wished to be performed.   
// similar to the first argument, the second is also an array of the remaining arguments.

return {
        strings, // array of the literals
        values   // array of the values
    };
}
Enter fullscreen mode Exit fullscreen mode

A showcase example:
Suppose we want to automatically uppercase the first interpolated value.

function upper(strings, ...values) {

    let result = "";
        result += strings[0];
        result += values[0].toUpperCase();

    return result;
}

const name = "John";


//Notice how we are calling the function
console.log(
    upper`Hello ${name}!`   
);

//Hello JOHN!
Enter fullscreen mode Exit fullscreen mode

To be continued...

Top comments (0)