JavaScript Template Literals are a powerful tool for creating strings. They allow you to easily embed expressions, variables, and other data into your strings. Template literals are especially useful when dealing with dynamic content, such as when building web applications.
let name = 'world';
let greeting = `Hello, ${name}!`;
console.log(greeting);
In this example, we are using template literals to create a string with a placeholder. The placeholder is indicated by the dollar sign and curly braces ( ${ } ). The placeholder is then replaced with the value of the variable, in this case, the string "world".
let html = `
<div>
<h1>Hello World</h1>
</div>
`;
console.log(html);
In this example, we are using template literals to create a multi-line string. This eliminates the need for escape characters (\n) to create line breaks.
let num1 = 10;
let num2 = 20;
let result = `The result is ${num1 + num2}`;
console.log(result);
In this example, we are using template literals to create a string with an expression. The expression is indicated by the dollar sign and curly braces ( ${ } ). The expression is then evaluated and the result is inserted into the string.