Kodeclik Logo

Learn More

Fall 2025

Kodeclik Blog

Formatting your Javascript strings

You often need to build human-readable messages from variables—UI labels, logs, emails, receipts, etc. Good formatting makes code clearer, reduces bugs (like missing spaces), and helps with numbers/dates and multi-line layouts.

Table of Contents


Example

Method 1: Basic string concatenation

Method 2: A custom formatting function

Method 3: Use Template literals (backticks)

Things to be careful about

Practical application: rendering a receipt line

Summary

Example

Consider the following example. Assume you are given the following Javascript variables:

const name = "Ava";
const items = 3;
const total = 42.5;

Our goal is to format these values into the following (composite) string:

Javascript string formatting
Hello Ava — you bought 3 items for $42.50.

Below are three ways to do it.

Method 1: Basic string concatenation

We can use the basic string concatenation operator “+” to achieve this effect:

const name = "Ava";
const items = 3;
const total = 42.5;

const msg = "Hello " + name + " — you bought " + items + " items for $" + total.toFixed(2) + ".";
console.log(msg);
// Hello Ava — you bought 3 items for $42.50.

This code joins smaller strings and variable values together using +. total.toFixed(2) makes sure the number is shown with two decimal places (like money). The final result is one long string that combines text and values exactly as we want.

Method 2: A custom formatting function

Here, we build our own simple formatter for readability and reuse. As in the previous example, we support {name}, {items}, {total} tokens and let callers plug in a number formatter.

const name = "Ava";
const items = 3;
const total = 42.5;

function format(template, values, formatters = {}) {
  return template.replace(/\{(\w+)\}/g, (_, key) => {
    const val = values[key];
    return key in formatters ? formatters[key](val) : String(val);
  });
}

const dollars = n => n.toFixed(2);

const msg = format(
  "Hello {name} — you bought {items} items for ${total}.",
  { name, items, total },
  { total: dollars }
);

console.log(msg);
// Hello Ava — you bought 3 items for $42.50.

Here, the function format() looks through the text and replaces each placeholder (like {name}) with its actual value. If a special formatter is provided (for example, dollars), it applies that to the value first. This approach lets you reuse the same pattern for many different messages in your program.

Method 3: Use Template literals (backticks)

This is a modern approach: it is terse, multi-line, and expression-friendly.

const name = "Ava";
const items = 3;
const total = 42.5;

const msg = `Hello ${name} — you bought ${items} items for $${total.toFixed(2)}.`;
console.log(msg);
// Hello Ava — you bought 3 items for $42.50.

This method uses backticks (`) instead of quotes. You can place variables directly inside ${...} and JavaScript will automatically insert their values. It’s cleaner, easier to read, and works great for multi-line strings.

Things to be careful about

When working with string formatting, here are a few simple things to remember:

  • Backticks: If you ever need an actual backtick inside your text, write it as \` so it doesn’t confuse Javascript.
  • Missing values: If a variable might be null or undefined, give it a default value with code like ${name || "Guest"}.
  • Formatting numbers and money: Use the Intl.NumberFormat feature to display numbers properly for your region.
  • Avoid HTML injection: When showing user input on a webpage, don’t build HTML using string concatenation—use DOM methods instead.
  • Spaces: When concatenating manually, be careful not to miss spaces between words; template literals make this much easier.

Practical application: rendering a receipt line

Imagine you’re making an online store and want to print each line of a receipt nicely formatted.

function receiptLine({ name, qty, price, locale = "en-US", currency = "USD" }) {
  const money = new Intl.NumberFormat(locale, { style: "currency", currency });
  const total = qty * price;
  return `${name} — ${qty} × ${money.format(price)} = ${money.format(total)}`;
}

console.log(receiptLine({ name: "Notebook", qty: 3, price: 4.25 })); 
// Notebook — 3 × $4.25 = $12.75

Here, Intl.NumberFormat is used to format prices as currency, so they look correct for different countries. The function calculates the total (qty * price) and uses a template literal to build the line in a clean and readable way.

Summary

String formatting in Javascript lets you combine text and variables to create clear, professional-looking messages. You can use concatenation for quick tasks, custom functions for reusable templates, or template literals for simple, modern, and readable code. For most cases, template literals are the best choice—they make your code shorter, easier to maintain, and less prone to mistakes.

Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2025. All rights reserved.