JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JS String Templates


📘 JavaScript String Templates – Template Literals in ES6

Template literals (also known as template strings) allow you to embed variables and expressions inside a string using backticks `, and ${...} syntax.

Introduced in ES6, template literals are more flexible than regular strings.


🔹 Syntax

let name = "John";
let greeting = `Hello, ${name}!`;  // Output: Hello, John!

✅ Template literals are enclosed in backticks: `, not quotes.


🔹 Features of Template Literals

Feature Description Example
Variable interpolation Embed variables using ${} `Hello, ${name}`
Expression evaluation Perform operations inside ${} `2 + 2 = ${2 + 2}`2 + 2 = 4
Multiline support Supports multiline strings without \n `Line1\nLine2` prints as two lines
Function calls Can call functions inside ${} `Welcome ${getName()}`

🔹 Examples

let product = "Book";
let price = 299;
let message = `The price of ${product} is ₹${price}.`;
console.log(message);  // Output: The price of Book is ₹299

let multiline = `This is line 1
This is line 2`;
console.log(multiline);

🔹 Expressions in Template Strings

let a = 5;
let b = 10;
let result = `The sum of ${a} and ${b} is ${a + b}`;
console.log(result); // "The sum of 5 and 10 is 15"

Practice Questions

Q1. How do you include a variable user = "Alice" in the string "Welcome, Alice!" using a template literal?

Q2. How do you print a multiline message using a single template string?

Q3. What is the output of this code: `2 + 3 = ${2 + 3}`?

Q4. How can you display "Total: $100" by inserting a variable amount = 100 into the string?

Q5. How do you write "Today is Sunday" using a variable day = "Sunday" and a template literal?

Q6. How do you call a function getUserName() inside a template literal to greet the user?

Q7. What happens if you use single or double quotes instead of backticks with ${}?

Q8. How do you use a template literal to combine two variables: first = "Good" and second = "Morning"?

Q9. Write a string using template literals to display "10 * 2 = 20" by evaluating inside ${}.

Q10. How do you show "Length of name is 4" using a variable name = "John"?


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top