What is a Template Literal & How is it used ?
Last Updated :
14 Feb, 2024
What is template literal?
A template literal is simply string literals surrounded by double backticks (`). Such seemingly simple syntax opens up a treasure trove of opportunities as strings can span several lines and accept dynamic values effortlessly, thanks to expressions embedded within them.
Syntax:
`string text ${expression} string text`
Note: Within this term, ${expression} describes an embedded expression which can be any valid JavaScript expression. it may range from variables to functions or even more complicated computational rules.
Single Line template literal:
const name = 'geek';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, John!
Multi-line template literal:
const poem = `
Roses are red,
Violets are blue,
Sugar is sweet,
And so are you.
`;
console.log(poem);
Example: This example shows the use of the single-line template literal. we can access any variable inside the template literal with the help of the “${varibale_name}” syntax.
Javascript
const name = 'geek' ;
const greeting = `Hello, ${name}!`;
console.log(greeting);
|
Example: This example shows the use of a multi-line template literal.
Javascript
const poem = `
hello geek,
welcome to GFG,
Try to learn cpp,
And other programming langugae.
`;
console.log(poem);
|
Output
hello geek,
welcome to GFG,
Try to learn cpp,
And other programming langugae.
Share your thoughts in the comments
Please Login to comment...