䷓Understanding Template Literals
Template literals in JavaScript, also known as template strings or string templates, are a flexible way to work with strings. They allow you to easily include variables, expressions, and multi-line text within a string, making string creation more readable and convenient.
🧩 Back-Tics Syntax
Template Strings use back-ticks (``) rather than the quotes ("") to define a string.
let text = `Hello World!`; //Hello world!✅ Quotes Inside Strings
Template Strings allow both single and double quotes inside a string.
let text = `He's often called "Johnny"`; //He's often called "Johnny"🔰 Multiline Strings
Template Strings allow multiline strings.
let text =`The quick
brown fox
jumps over
the lazy dog`; //The quick brown fox jumps over the lazy dog⚡ Interpolation
Template String provide an easy way to interpolate variables and expressions into strings. The method is called string interpolation.
The syntax is : ${...}
let name = "John";
let age = 21;
let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message); //Hello, my name is John and I am 21 years old.💠 Variable Substitutions
Template Strings allow variables in strings.
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!`; //Welcome John, Doe!Automatic replacing of variables with real values is called string interpolation.
🏷️ Expression Substitution
Template Strings allow expressions in strings.
let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`; //12.50Automatic replacing of expressions with real values is called string interpolation.