How to format strings with variables in JavaScript
To format a string with variables in JavaScript, you can use template literals, string concatenation, and other methods. Let's dive into the different ways to format strings with variables in JavaScript.

How to format strings with variables in JavaScript?
String formatting with variables is a crucial skill in JavaScript programming. Whether you're creating dynamic messages, building templates, or working with user data, knowing how to combine strings with variables efficiently will make your code cleaner and more maintainable.
Template Literals (Template Strings)
Template literals, introduced in ES6, are the modern way to format strings with variables in JavaScript. They use backticks (`) and $ for variable interpolation. Backticks are different from single quotes and double quotes. They allow you to use variables and expressions inside the string without concatenation.
Basic Syntax and Usage
Take the following example on how to create strings with variables in JavaScript:
1// Basic template literal2const name = 'John';3const greeting = `Hello, ${name}!`;4console.log(greeting); // Output: Hello, John!56// Multiple variables7const item = 'coffee';8const price = 4.99;9const message = `Your ${item} costs $${price}`;10console.log(message); // Output: Your coffee costs $4.991112// Expressions inside template literals13const quantity = 3;14const total = `Total: $${quantity * price}`;15console.log(total); // Output: Total: $14.97
As demonstrated in the example above, you can use backticks to create strings with variables in JavaScript. Also take note that you must use the dollar sign ($) with curly braces ({}) to interpolate the variables.
Multiline Strings
Template literals make it easy to create multiline strings:
1const email = `2Dear ${name},34Thank you for your order of ${quantity} ${item}(s).5Your total is $${quantity * price}.67Best regards,8The Store Team9`;1011console.log(email);1213// Output:14// Dear John,15//16// Thank you for your order of 3 coffee(s).17// Your total is $14.97.18//19// Best regards,20// The Store Team
String Concatenation Methods
While template literals are preferred, it's important to know other string formatting methods:
1// Using the + operator2const name = 'Jane';3const age = 25;4const message1 = 'My name is ' + name + ' and I am ' + age + ' years old.';56// Using concat()7const message2 = ''.concat('My name is ', name, ' and I am ', age, ' years old.');89// Using join()10const message3 = ['My name is', name, 'and I am', age, 'years old'].join(' ');1112// Modern approach with template literals13const message4 = `My name is ${name} and I am ${age} years old.`;
Number Formatting
JavaScript provides several powerful methods for formatting numbers, especially when working with currency values. Let's explore the key approaches:
1const price = 1234.5678;23// Basic decimal formatting with toFixed()4// toFixed() rounds to specified decimal places5const formattedPrice = `$${price.toFixed(2)}`; // $1234.576const roundedPrice = `$${price.toFixed(0)}`; // $123578// Using Intl.NumberFormat for locale-aware formatting9// This is the recommended way to format currency10const formatter = new Intl.NumberFormat('en-US', {11 style: 'currency',12 currency: 'USD',13 minimumFractionDigits: 2,14 maximumFractionDigits: 215});16const currencyString = formatter.format(price); // $1,234.571718// Other number formatting options19const percentFormatter = new Intl.NumberFormat('en-US', {20 style: 'percent',21 minimumFractionDigits: 122});23const percentage = percentFormatter.format(0.3467); // 34.7%2425// Formatting large numbers26const bigNumber = 1234567.89;27const numberFormatter = new Intl.NumberFormat('en-US');28const formattedBigNumber = numberFormatter.format(bigNumber); // 1,234,567.89
Date Formatting
JavaScript's Date object combined with template literals offers flexible date formatting options. Here's a comprehensive look:
1const date = new Date();23// Basic date formatting methods4const simpleDate = `Date: ${date.toLocaleDateString()}`; // e.g., "3/14/2024"5const simpleTime = `Time: ${date.toLocaleTimeString()}`; // e.g., "2:30:45 PM"6const fullDateTime = `DateTime: ${date.toLocaleString()}`; // e.g., "3/14/2024, 2:30:45 PM"78// Advanced formatting with options9const options = {10 weekday: 'long', // full weekday name11 year: 'numeric', // 4-digit year12 month: 'long', // full month name13 day: 'numeric', // day of the month14 hour: '2-digit', // 2-digit hours15 minute: '2-digit', // 2-digit minutes16 timeZoneName: 'short' // time zone abbreviation17};18const fullDate = `Today is ${date.toLocaleDateString('en-US', options)}`;19// e.g., "Today is Thursday, March 14, 2024, 02:30 PM EST"2021// Formatting specific date components22const monthNames = ['January', 'February', 'March', 'April', 'May', 'June',23 'July', 'August', 'September', 'October', 'November', 'December'];24const customDate = `${monthNames[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`;25// e.g., "March 14, 2024"
Common Use Cases
1. Dynamic HTML Templates
1const user = {2 name: 'Alice',3 avatar: 'avatar.jpg',4 role: 'Admin'5};67const userCard = `8 <div class="user-card">9 <img src="${user.avatar}" alt="${user.name}'s avatar">10 <h2>${user.name}</h2>11 <span class="role">${user.role}</span>12 </div>13`;
2. URL Construction
URL construction is a common use case for template literals, especially when building API endpoints or navigation links. Template literals make it easy to combine multiple URL components in a clean and readable way.
1const baseUrl = 'https://api.example.com';2const endpoint = 'users';3const id = 123;4const query = 'status=active';56// Template literals allow us to cleanly combine URL parts7const url = `${baseUrl}/${endpoint}/${id}?${query}`;8// https://api.example.com/users/123?status=active910// This is much cleaner than concatenation:11// const url = baseUrl + '/' + endpoint + '/' + id + '?' + query;1213// You can also handle multiple query parameters:14const queryParams = {15status: 'active',16role: 'admin',17limit: 1018};19const queryString = Object.entries(queryParams)20.map(([key, value]) => `${key}=${value}`)21.join('&');2223const urlWithMultipleParams = `${baseUrl}/${endpoint}?${queryString}`;24// https://api.example.com/users?status=active&role=admin&limit=10
Template literals are particularly useful for URL construction because they:
- Eliminate the need for messy string concatenation
- Make the URL structure visually clear
- Allow easy insertion of variables and parameters
- Support multi-line formatting for complex URLs
Best Practices
-
Use Template Literals by Default
- More readable and maintainable
- Better handling of multiline strings
- Cleaner syntax for variable interpolation
-
Format Numbers and Dates Appropriately
- Use toFixed() for decimal precision
- Utilize Intl.NumberFormat for localized numbers
- Apply toLocaleDateString() for dates
-
Handle Edge Cases
- Check for null or undefined values
- Provide default values when needed
- Sanitize user input
-
Keep it Clean
- Break long strings into smaller parts
- Use meaningful variable names
- Comment complex string formatting logic
Practice Examples
Try these exercises to improve your string formatting skills:
- Create a template for an email notification system
- Build a dynamic URL builder with multiple parameters
- Format a complex data object into a readable string
Test your knowledge with these practice questions:
How to Concatenate Strings Using Template Literals in JavaScript to Create a Greeting Message
Ready to master JavaScript string formatting? Join TechBlitz for daily coding challenges, personalized learning paths, and a supportive community of developers. Start your journey today at TechBlitz.
Learn to code, faster
Join 810+ developers who are accelerating their coding skills with TechBlitz.