DEV Community

Alessio Michelini
Alessio Michelini

Posted on

Template Literals: Why Indentation Matters (Especially for AI Prompts)

I've heard this argument quite a few times recently, especially in code related to prompt engineering, and sometimes the most trivial things can stir up quite a conversation between developers.

You might see some code like this:

const myFunc = async () => {
  try {
    if (condition) {
      const prompt = `Hello world
                      This is some multiline text
                      More text
`;
    }
  } catch {
    // some stuff here
  }
}
Enter fullscreen mode Exit fullscreen mode

Many developers think that's the right way to write a multiline string, as everything is indented according to the rest of the code. But there are two major issues with this approach.

This is a template literal

While at first glance the indentation might seem to make sense, when using a template literal (the string wrapped with backticks), you don't need to follow the rest of the code's indentation. That's because when that variable is rendered, it will look like this:

Hello world
              This is some multiline text
              More text
Enter fullscreen mode Exit fullscreen mode

As you can see, that doesn't look correct at all — the extra spaces or tabs are taken into account and become part of the actual string content.

Instead, according to the language specifications, you should write the same code like this:

const myFunc = async () => {
  try {
    if (condition) {
      const prompt = `Hello world
This is some multiline text
More text
`;
    }
  } catch {
    // some stuff here
  }
}
Enter fullscreen mode Exit fullscreen mode

Empty spaces count as tokens

Another issue with the original code, especially when dealing with AI prompts, is that extra spaces or tabs count as tokens, which then translates to higher costs.

It might seem like a small thing, but when dealing with large amounts of text, it can start to make a real difference in your AI usage costs.

You can test this yourself by using OpenAI's tokenizer tool. The same text we used above, without the extra spaces, generates 11 tokens, while the one with the extra spaces generates 14 tokens.

With extra spaces

Without extra spaces

The bottom line

When working with template literals, especially for prompt engineering, always remember that what you see in your code editor is exactly what gets sent to the AI model. Those extra spaces and tabs aren't just visual clutter — they're actual content that affects both the quality of your prompts and your costs.

Keep your template literals clean and properly formatted, and your future self (and your budget) will thank you!

Disclaimer: AI was used to reformat this article and correct errors

Top comments (0)