What is Template Literals in JavaScript | JavaScript Tutorials in Hindi | Interview Question #48
Template literals are a feature in JavaScript that provide an easier and more readable way to work with strings. They are enclosed by backticks (`
) instead of single (”) or double (“”) quotes. Template literals offer several advantages over traditional string concatenation methods, such as:
- String Interpolation: Embedding expressions within strings.
- Multi-line Strings: Creating strings that span multiple lines without special character
String Interpolation
With template literals, you can embed expressions directly into strings using the ${...}
syntax. This is particularly useful for combining variables and expressions within a string.
const name = 'John';
const age = 30;
const message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message); // Output: Hello, my name is John and I am 30 years old.
Multi-line Strings
Template literals make it easy to create multi-line strings without the need for escape characters or concatenation.
const multiLineString = `This is a string
that spans across
multiple lines.`;
console.log(multiLineString);
// Output:
// This is a string
// that spans across
// multiple lines.
What is #Template #Literals in #JavaScript | JavaScript #Tutorials in #Hindi | #Interview #Question #48
Template literals are a powerful feature in JavaScript that simplify the creation and manipulation of strings. They provide a more readable and concise way to interpolate variables and expressions, create multi-line strings, and even define custom string processing functions through tagged templates.