Home > Web Front-end > JS Tutorial > Why Do My JavaScript Template Literals Display Variable Names Instead of Values?

Why Do My JavaScript Template Literals Display Variable Names Instead of Values?

Patricia Arquette
Release: 2024-12-08 05:56:09
Original
233 people have browsed it

Why Do My JavaScript Template Literals Display Variable Names Instead of Values?

Template Literals in JavaScript: Backticks Required

Template literals in JavaScript, denoted by ${} placeholders within strings, offer a convenient way to embed expressions. However, encountering display issues with template literals using single quotes (') instead of backticks (`) is a common oversight.

Problem Description

When using single quotes, the literal variable names are printed instead of their values. For instance:

console.log('categoryName: ${this.categoryName}\ncategoryElements: ${this.categoryElements} ');
Copy after login

Output:

${this.categoryName}
categoryElements: ${this.categoryElements}
Copy after login

Solution

JavaScript template literals require backticks, not straight quotation marks.

Backticks are the characters next to the '1' key on a QWERTY keyboard. Using them instead of single quotes creates a template literal, which can then house ${} placeholders to evaluate expressions:

categoryName = "name";
categoryElements = "element";
console.log(`categoryName: ${this.categoryName}\ncategoryElements: ${categoryElements} `);
Copy after login

Output:

categoryName: name 
categoryElements: element
Copy after login

Additional Information

Backticks are frequently used in various programming languages but may be novel to JavaScript developers. Refer to the following resource for further details:

  • [Usage of the Backtick Character in JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_literals)

The above is the detailed content of Why Do My JavaScript Template Literals Display Variable Names Instead of Values?. 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