Home > Web Front-end > JS Tutorial > How Do Backticks Affect JavaScript Function Calls and What are Tagged Templates?

How Do Backticks Affect JavaScript Function Calls and What are Tagged Templates?

Patricia Arquette
Release: 2024-11-25 03:48:12
Original
810 people have browsed it

How Do Backticks Affect JavaScript Function Calls and What are Tagged Templates?

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"]));
Copy after login

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"] }]
Copy after login
Copy after login

When this array is passed to console.log, the array itself is logged, resulting in the observed output:

["1", { raw: ["1"] }]
Copy after login
Copy after login

Advantages of Tagged Templates

Tagged templates offer several advantages over traditional string manipulation methods:

  • Enhanced string filtering and escaping.
  • Template string interpolation with complex logic.
  • Increased code readability and maintainability.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template