How to Create a String with Variables in JavaScript?
To create a string with variables in JavaScript, you can use several methods, including string concatenation, template literals, and the String
methods. Here are the common approaches:
1. Template Literals (Recommended)
Template literals are the modern and most preferred way to create strings with variables. They use backticks (`
) and allow embedded expressions using ${}
syntax.
Example:
const name = "Alice";
const age = 30;
const message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message); // Output: Hello, my name is Alice and I am 30 years old.
Output
Hello, my name is Alice and I am 30 years old.
2. String Concatenation Using the +
Operator
This is the traditional way to build strings by concatenating string literals and variables using the +
operator.
Example:
const name = "Bob";
const age = 25;
const message = "Hello, my name is " + name + " and I am " + age + " years old.";
console.log(message); // Output: Hello, my name is Bob and I am 25 years old.
Output
Hello, my name is Bob and I am 25 years old.
3. Using the String.concat()
Method
You can also use the String.concat()
method to join strings and variables. This method is less commonly used for simple string construction but can be handy in some situations.
Example:
const firstName = "Charlie";
const lastName = "Brown";
const fullName = "".concat(firstName, " ", lastName);
console.log(fullName); // Output: Charlie Brown
Output
Charlie Brown
4. Using String Interpolation Functions (Older Methods)
In the past, developers used functions like sprintf()
from libraries, but these are largely obsolete due to the simplicity of template literals.
Which Method to Use?
- Template literals (backticks and
${}
syntax) are recommended for creating strings with variables because they are more readable, support multi-line strings, and make it easy to include expressions and complex formatting. - Concatenation is fine for simpler cases but can get messy for longer strings.
Example Comparison
const item = "laptop";
const price = 999.99;
// Using template literals (Recommended)
const msg1 = `The price of the ${item} is $${price}.`;
// Using string concatenation
const msg2 = "The price of the " + item + " is $" + price + ".";
console.log(msg1); // Output: The price of the laptop is $999.99.
console.log(msg2); // Output: The price of the laptop is $999.99.
Output
The price of the laptop is $999.99. The price of the laptop is $999.99.