JavaScript Template Literals

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.

Why should you use it?

  • Template literals make it easier to create dynamic strings.
  • Template literals are more readable and easier to maintain than string concatenation.
  • Template literals are more secure than string concatenation as they don’t allow for injection attacks.

Template Literals

Template literals are a new feature in JavaScript, introduced in ES6, that provides a way to create strings using backticks (`) instead of single or double quotes. Template literals can contain placeholders, which are indicated by the dollar sign and curly braces ( ${ } ). This allows you to easily insert variables into a string without having to use string concatenation. Template literals also allow for multi-line strings, which can be useful for HTML or CSS. This eliminates the need for escape characters (\n) to create line breaks. Template literals also allow you to use expressions within the string. This is done by wrapping the expression in ${ }.

Example

script.js
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".

Multi-Line String

script.js
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.

Expression

script.js
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.