HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

JavaScript Template Strings

JavaScript Template Strings, also known as template literals, provide a way to create multi-line strings and embed expressions within them. They offer a more readable and convenient syntax compared to traditional string concatenation.

Here's how you can use template strings:

Basic Syntax:

Template strings are enclosed in backticks (`), not single or double quotes.

Example

const name = "John";
const greeting = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, John!
 

Embedded Expressions:

You can embed expressions within template strings using ${}. These expressions are evaluated and their results are inserted into the string.

Example

const a = 10;
const b = 20;
const sum = `The sum of ${a} and ${b} is ${a + b}.`;
console.log(sum); // Output: The sum of 10 and 20 is 30.
 

Multi-line Strings:

Template strings support multi-line strings without the need for special characters like \n.

Example

const multiLine = `
  This is 
  a multi-line
  string.`;
console.log(multiLine);
/* Output:
  This is 
  a multi-line
  string.
*/

Tagged Templates:

Template strings can be "tagged" with a function that processes the template literal and its embedded expressions..

Example

function tag(strings, ...values) {
  console.log(strings); // Array of string literals
  console.log(values); // Array of interpolated values
}

const name = "John";
const age = 30;
tag`Hello, my name is ${name} and I am ${age} years old.`;
/* Output:
  ["Hello, my name is ", " and I am ", " years old."]
  ["John", 30]
*/
  

Escaping Backticks:

If you need to include a backtick inside a template string, you can escape it with a backslash.

Example

const withBacktick = `This string contains a \`backtick\`.`;
console.log(withBacktick); // Output: This string contains a `backtick`.