About Lesson
JavaScript Template Literals
-
Enhanced String Literals: Template literals are a powerful feature in JavaScript that provide a more convenient way to create strings.
-
Syntax:
- Enclosed within backticks (“).
- Allow for embedded expressions within the string, using the dollar sign and curly braces:
${expression}
.
-
Example:
JavaScriptconst name = "John"; const age = 30; const greeting = `Hello, my name is ${name} and I am ${age} years old.`; console.log(greeting); // Output: "Hello, my name is John and I am 30 years old."
-
Benefits:
- Easier to read and write: Improved string readability, especially for multiline strings.
- Embedded expressions: Seamlessly integrate variables and expressions within strings.
- String interpolation: Simplify string concatenation.
-
Multi-line Strings:
JavaScriptconst message = `This is a multiline string.`;
-
Tagged Templates:
- Allow you to create custom string processing functions.
- The first argument to the tag function is an array containing the literal parts of the template.
- Subsequent arguments represent the values of the embedded expressions.
JavaScriptfunction highlight(strings, ...values) { let str = ''; for (let i = 0; i < values.length; i++) { str += strings[i] + `<b>${values[i]}</b>`; } str += strings[strings.length - 1]; return str; } const name = "John"; const highlightedName = highlight`Hello, ${name}!`;
Template literals significantly enhance string manipulation in JavaScript, making it easier to create dynamic and complex strings.