Backticks in JavaScript: Function Invocation or String Tagging?
When using backticks (...) in JavaScript, you may encounter unexpected behaviors, such as when executing console.log with a single parameter inside backticks:
console.log`1`;
Producing output like:
console.log`1` VM12380:2 ["1", raw: Array[1]]
Understanding Tagged Templates
This behavior arises from the concept of tagged templates introduced in ES6. Tagged templates are functions that can be used along with backticks to manipulate string literals. When a tagged template is invoked, it receives two parameters:
Function Invocation vs. Tagging
In the case of console.log with backticks, the backticks are not invoking the function. Instead, they are tagging the string literal "1" with the console.log function. The resulting tagged template function returns an array containing the transformed value.
Specifically:
Transpilation
Modern browsers transpile ES6 code to make it compatible with older JavaScript versions. In this case, the tagged template function is transpiled to a regular function call:
var _taggedTemplateLiteralLoose = function (strings, raw) { strings.raw = raw; return strings; }; console.log(_taggedTemplateLiteralLoose(["1"], ["1"]));
The _taggedTemplateLiteralLoose function returns an array that is passed to the console.log function, which prints the array.
Conclusion
Backticks in JavaScript can be used for both string interpolation and tagged templates. When used with a tagged template function, the function receives parsed values of the string literals and embedded values, enabling the manipulation and transformation of data before outputting it.
The above is the detailed content of JavaScript Backticks: String Interpolation or Tagged Template Function?. For more information, please follow other related articles on the PHP Chinese website!