Programming Tutorials

Template literals vs String concatenation in JavaScript

By: Terrence in Javascript Tutorials on 2023-04-25  

Template literals and string concatenation are two ways to combine strings in JavaScript.

String concatenation involves joining strings together using the + operator. For example:

const firstName = "John";
const lastName = "Doe";
const fullName = firstName + " " + lastName;

console.log(fullName); // "John Doe"

Template literals use backticks (`) to define a string that can contain variables, expressions, and multi-line strings. Variables and expressions are enclosed in ${}. For example:

const firstName = "John";
const lastName = "Doe";
const fullName = `${firstName} ${lastName}`;

console.log(fullName); // "John Doe"

Template literals also allow multi-line strings without the need for escaping newlines or using concatenation. For example:

const message = `
  Hello,
  
  This is a multi-line message.
  
  Thank you for reading.
`;

console.log(message);

Using template literals can be more readable and maintainable, especially when working with complex strings that involve many variables and expressions. They can also make the code less error-prone, since you don't have to worry about missing or extra string concatenation operators.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Javascript )

Latest Articles (in Javascript)