Backticks Calling Functions in JavaScript: Demystifying Tagged Templates
When executing JavaScript code that incorporates backticks, such as console.log1`, some users have encountered unexpected output. This behavior stems from tagged templates in ES-6, which allow customized string manipulation.
Understanding Tagged Templates
Tagged templates are template literals preceded by a special function, like console.log. These functions receive the parsed values of template strings along with their raw unparsed counterparts.
In the case of console.log1, the tag function is console.log. It accepts two parameters: strings (an array of string literals) and values` (an array of interpolated values).
The Output Explanation
When console.log1` is executed, the JavaScript engine transpiles the ES6 code to ES5. The transpiled code resembles the following:
console.log(_taggedTemplateLiteralLoose(["1"], ["1"]));
Here, _taggedTemplateLiteralLoose is a transpiled function that assigns the raw string literal to the raw property of the strings array.
The tagged template literal, therefore, returns an array with the following structure:
["1", { raw: ["1"] }]
When this array is passed to console.log, the array itself is logged, resulting in the observed output:
["1", { raw: ["1"] }]
Advantages of Tagged Templates
Tagged templates offer several advantages over traditional string manipulation methods:
The above is the detailed content of How Do Backticks Affect JavaScript Function Calls and What are Tagged Templates?. For more information, please follow other related articles on the PHP Chinese website!