Table of contents
1.
Introduction
2.
Using the concatenation Method
2.1.
JavaScript
3.
Using backticks
3.1.
JavaScript
3.2.
JavaScript
4.
Using String interpolation
4.1.
JavaScript
4.2.
JavaScript
5.
Frequently Asked Questions
5.1.
Can I use single quotes or double quotes instead of backticks for string interpolation?
5.2.
Is it possible to perform calculations or function calls within string interpolation?
5.3.
Are there any performance differences between concatenation, backticks, & string interpolation?
6.
Conclusion
Last Updated: Jul 10, 2024
Easy

JavaScript String Formatting

Author Rahul Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

JavaScript is a powerful & versatile programming language used for web development. One important aspect of JavaScript is string formatting, which allows you to manipulate & combine strings in various ways. 

JavaScript String Formatting

This article will explain different methods for formatting strings in JavaScript, which are concatenation, using backticks, & string interpolation. 

Using the concatenation Method

One of the most basic ways to format strings in JavaScript is by using the concatenation method. Concatenation involves joining two or more strings together using the plus (+) operator. 

Here's an example:

  • JavaScript

JavaScript

let firstName = "Rahul";

let lastName = "Sharma";

let fullName = firstName + " " + lastName;

console.log(fullName);
You can also try this code with Online Javascript Compiler
Run Code

Output: 

"Rahul Sharma"


In this code, we have two variables firstName & lastName holding string values. We then use the + operator to concatenate these strings along with a space character in between. The resulting string is stored in the fullName variable.

Using backticks

Another way to format strings in JavaScript is using backticks (`). Backticks allow you to create template literals, which provide a more concise & readable way to include variables & expressions within a string. 

For example:

  • JavaScript

JavaScript

let firstName = "Rinki";

let lastName = "Patel";

let age = 20;

let introduction = `My name is ${firstName} ${lastName}, and I am ${age} years old.`;

console.log(introduction);
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

"My name is Rinki Patel, and I am 20 years old."


In this code, we use backticks to create a template literal. Inside the backticks, we can include variables or expressions by wrapping them in ${}. The values of firstName, lastName, & age are automatically inserted into the resulting string.

Using backticks & template literals makes the code more readable & easier to maintain, especially when dealing with multiple variables or complex expressions.

Here's another example that demonstrates the power of template literals:

  • JavaScript

JavaScript

let price = 9.99;

let quantity = 3;

let totalCost = `The total cost of ${quantity} items at $${price} each is $${(price * quantity).toFixed(2)}.`;

console.log(totalCost);
You can also try this code with Online Javascript Compiler
Run Code

 

Output: 

"The total cost of 3 items at $9.99 each is $29.97."


In this example, we use template literals to create a string that includes the price, quantity, & the calculated total cost. The expressions ${quantity}, $${price}, & $${(price * quantity).toFixed(2)} are evaluated & their values are inserted into the string.

Using String interpolation

String interpolation is another way to format strings in JavaScript, similar to using backticks & template literals. It allows you to embed expressions or variables directly within a string. 

For example:

  • JavaScript

JavaScript

let name = "Harsh";

let grade = "A";

let message = `Congratulations, ${name}! You have achieved an ${grade} grade in the exam.`;

console.log(message);
You can also try this code with Online Javascript Compiler
Run Code


Output:

"Congratulations, Harsh! You have achieved an A grade in the exam."


In this code, we use the ${} syntax to interpolate the values of name & grade into the string. The expressions inside ${} are evaluated, & their values are inserted into the resulting string.

String interpolation provides a clean & concise way to include dynamic values within a string. It eliminates the need for manual concatenation & improves code readability.

An example that showcases string interpolation with a ternary operator:

  • JavaScript

JavaScript

let age = 17;

let message = `You are ${age >= 18 ? "eligible" : "not eligible"} to vote.`;

console.log(message);
You can also try this code with Online Javascript Compiler
Run Code


Output: 

"You are not eligible to vote."


In this example, we use string interpolation along with a ternary operator to conditionally include a value in the string. The expression age >= 18 ? "eligible" : "not eligible" evaluates to "eligible" if age is greater than or equal to 18, & "not eligible" otherwise.

Frequently Asked Questions

Can I use single quotes or double quotes instead of backticks for string interpolation?

No, string interpolation only works with backticks (). Single quotes or double quotes will treat the ${}` as a literal string.

Is it possible to perform calculations or function calls within string interpolation?

Yes, you can include any valid JavaScript expression inside the ${} syntax, including calculations, function calls, or even nested interpolations.

Are there any performance differences between concatenation, backticks, & string interpolation?

In terms of performance, there is no significant difference between these methods. However, string interpolation & backticks offer better readability & maintainability.

Conclusion

In this article, we have learned about various methods for formatting strings in JavaScript. We learned concatenation, using backticks, & string interpolation. Concatenation is a basic approach to joining strings, while backticks & string interpolation provides more concise & readable ways to include variables & expressions within a string.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass