Backticks and Function Invocation in JavaScript
When using backticks () to wrap a string literal in JavaScript, you may encounter unexpected behavior such as a tagged template being invoked. In this case, console.log1 resulted in the output "console.log1`nVM12380:2 ["1", raw: Array[1]]".
Tagged Templates in ES6
The explanation lies in the concept of tagged templates, introduced in ES6. Tagged templates allow you to tag a template string with a function. When the string is used with the function, the function receives the parsed values of the template string and the values in the string.
Function as a Tag
In the example provided, console.log is used as the tag function. It's effectively called with the parsed string values and the literal string value as an array. The function can then manipulate these values and return a new string or pass them along for further processing.
Returned Array
The console.log function does not perform any special processing on the values, so it returns the array containing the literal string value. This array is then printed out by console.log, resulting in the output you observed.
Transpilation and Template Literals
When using modern JavaScript features like template literals with older browsers, Babel or similar transpilers are used to convert the code to ES5, which is supported by these browsers. The transpiled code for the example would be:
console.log(_taggedTemplateLiteralLoose(["1"], ["1"]));
This transpiled code creates an array containing the literal string "1" and passes it to console.log as an argument.
Therefore, the backtick notation 1 is invoking console.log as a tagged template function, which returns an array that is then printed out. The raw property in the returned array contains the literal string value.
The above is the detailed content of Why Does `console.log\\`1`` Return an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!