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

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /