Template Literals in JavaScript

Template Literals in JavaScript

✨ Template Literals in JavaScript

Write cleaner strings with powerful expressions!

📌 What are Template Literals?

Template literals are strings defined using backticks ` ` instead of quotes. They allow:

  • Multiline strings
  • String interpolation (embed expressions)
  • Better readability

🧪 Syntax

const name = 'Aman';
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, Aman!"

🧩 Key Features

1️⃣ Multiline Strings

const poem = `Roses are red,
Violets are blue,
JS is awesome,
And so are you!`;

2️⃣ Expression Evaluation

const a = 5, b = 10;
console.log(`Sum is ${a + b}`); // "Sum is 15"

3️⃣ Nesting Functions

function upper(str) {
  return str.toUpperCase();
}
const user = "dev";
console.log(`Hello ${upper(user)}!`); // "Hello DEV!"

🚫 Without Template Literals

const name = 'Aman';
const msg = 'Hello, ' + name + '!';

✅ With Template Literals

const name = 'Aman';
const msg = `Hello, ${name}!`;

💡 Best Practices

  • Prefer backticks for dynamic or multiline strings
  • Use expressions inside ${} instead of string concatenation
  • Clean code = maintainable code

Post a Comment

Previous Post Next Post