What are template literals and tagged templates?
Suggested answer
Template literals use backticks and allow embedded expressions: `Hello, ${name}! You are ${age} years old.`. Support multi-line strings without \n. Expressions can be any valid JS (function calls, ternaries, arithmetic). Tagged templates: A function (tag) is placed before the template literal: tag`Hello ${name}`. The tag function receives:
1. An array of string segments between expressions.
2. The evaluated expression values as separate arguments. Example: function highlight(strings, ...values) { return strings.reduce((result, str, i) => result + str + (values[i] ? `<strong>${values[i]}</strong>` : ''), ''); } Tagged templates are used for: SQL/SOQL query builders that prevent injection, styled-components (CSS-in-JS), internationalisation libraries, and sanitising HTML.
Practice content for interview preparation; not an official vendor answer. Verify details against current product documentation.
Community comments (0)
No comments yet.
Sign in or create a free account to add a comment. Comments are moderated before they appear.