Before jumping to the topic, one might be interested in what string interpolation is. In JavaScript, a string is basically a sequence of one or more characters, usually consisting of symbols, letters, and numbers. String interpolation is the process used to evaluate a string literal, which contains one or more placeholders.
Thus, the placeholders are replaced with corresponding values, making it a more intuitive and straightforward string formatting model. With this in mind, let's find out how JavaScript string interpolation works and what standards are used.
A Note on Script Standards
JavaScript as a programming language complies with ECMAScript standards. This standard is used to ensure that all web pages on all web browsers operate properly. With ECMAScript 2021 (ES12 standard), the string interpolation is denoted by backticks, such as ``
.
Note that such backticks are also called template literals, and they are used mainly for string interpolation. The regular use of template literals looks like this:
const cucumbers = 5;
const tomatoes = 7;
console.log(`I have ${cucumbers} cucumbers`);
console.log(`I have ${cucumbers + tomatoes} vegetables`);
In this example, string interpolation is used to link a string (number) with a placeholder (vegetables, in this instance). If you run this code through a compiler, you'll get the following output:
I have 5 cucumbers
I have 12 vegetables
Multi-line strings
While the example with cucumbers and tomatoes is fine, string interpolation in JavaScript can also work with multi-line strings. Let's review the following code as a valid example:
console.log(`example: string text line
example: string text line 2`);
// "string text line 1
// string text line 2"
Try compiling these lines of code using a console, and you'll get the following output:
example: string text line 1
example: string text line 2
As you see, the output represents the placeholders' variables, which are expressed in multi-line strings. You can go even deeper, including more string lines to experiment with console outputs.
In the mentioned example, the syntax works differently since template literals eliminate the need for the following input: \n
between the string lines. This example will help you if you include more than a few lines, significantly simplifying syntax work.
Template literals expression
With template literals, it's also significantly easier to work with JavaScript, requiring less code and making it easier to read. Let's compare two embedded expressions, one using regular strings and the other one focusing on template literals.
Normal strings:
let a = 20;
let b = 40;
console.log('Sixty is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
// "Sixty is 60 and
// not 80."
Template literals:
let a = 20;
let b = 40;
console.log(`Sixty is ${a + b} and
not ${2 * a + b}.`);
// "Sixty is 60 and
// not 80."
When you compare the outputs one by one, you'll see that the template string usage is more manageable, uses less code, and has more functionality. For instance, try out adding a ternary operator alongside template literals.
Adding ternary operator
In regards to template literals you can even use a ternary operator. In JavaScript, it is most commonly used to assign a value to the variable if the condition is true
, with the same value if it appears to be false
. Let's review the following example:
const equipment = 26;
const maintenance = 68;
const total = equipment + maintenance;
const result = `The total bill is ${total}. ${total > 50 ? `Your card payment will be declined` : `Your card payment will be accepted`}.`
console.log(result);
Suppose you have only $50 on your credit card, and you need to buy both the equipment and pay for its maintenance upfront. With the aforementioned example, you include the variables, which indicate whether a specific condition can be met. If you change the values of equipment and maintenance to 15 and 25, the condition will be met and you'll get the following console message:
"Your card payment will be accepted."
If all the numbers are set as they are in the initial code, you'll get the following output in a console:
"Your card payment will be declined."
An example of including the ternary operator shows that you can combine template literals with other JavaScript functionality. Thus, it makes working with strings more accessible, once again requiring less manual input and code.
A word on raw strings
While working with strings, you can also test a special raw property. It can potentially be useful for accessing the raw strings as they were entered in code, fully omitting the processing of escape sequences. While it sounds a bit complicated, this property can help in the following situations:
function tag(strings) {
console.log(strings.raw[0]);
}
tag`string 1 \n string 2`;
// logs "string \n string 2" ,
// including the two characters '\' and 'n'
As you can see, you log only string 1 and string 2, at the same time including the two distinctive characters placed in the tag, such as \
and n
.
The critical point here is that this method functions as a tag, allowing substitutions to proceed but excluding espace sequences from the output. It can be helpful in tweaking template literals a bit more while adding properties to make your input more complex and nuanced.
Conclusion
String interpolation in JavaScript is a way to evaluate a string liberal and replace a corresponding placeholder with a designated value. This process is best conducted using template literals, as it allows experimenting with strings and placeholder variables, also allowing you to:
Write multi-line strings
Omit unnecessary syntax and make code more readable
Embed expressions with less input
Experiment with strings using a ternary operator
Use particular properties for more nuanced work with particular strings
For more information on template literals, don't hesitate to explore the ECMAScript standard and string properties.