String Formatting
String formatting means combining variables, text, and values inside a string to create dynamic output.
1. Traditional String Concatenation
Using + operator.
let name = "Jeeshma";
let age = 25;
console.log("My name is " + name + " and I am " + age + " years old.");
Output:
My name is Jeeshma and I am 25 years old.
Problems
As the string becomes longer, readability decreases.
2. Template Literals
Uses backticks ` `
Variables are inserted using ${}
let name = "Jeeshma";
let age = 25;
console.log(`My name is ${name} and I am ${age} years old.`);
Output:
My name is Jeeshma and I am 25 years old.
3. Expressions Inside Template Literals
You can perform calculations.
let a = 10;
let b = 20;
console.log(`Total: ${a + b}`);
Output:
Total: 30
4. Function Calls Inside Template Literals
function greet() {
return "Hello";
}
console.log(`${greet()} Jeeshma`);
Output:
Hello Jeeshma