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.
-> Tagged Template Literal
customFunction`My name is ${name} and I am ${age}.`
- Notice: The function name is written immediately before the backticks and it is without the parenthesis.
customFunction(`My name is ${name}`) // not like this
So what?
Internally, it becomes something like:
customFunction(
["My name is ", " and I am ", "."], // first argument
name, // second argument
age // third argument
);
-
The first argument contains an array of all the literal text.
["My name is ", " and I am ", "."] 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
};
}
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!
To be continued...
Top comments (0)