Do Backticks Preserve Spacing in JavaScript?

In JavaScript, using backticks (``) for multi-line strings, string interpolation, or tagged templates does preserve spacing, including any leading spaces, trailing spaces, and line breaks.

Consider, for example, the following where the backticks are used to define a multiline string:

const name = 'John';
const greeting = `
  Hello, ${name}!

  How are you today?


The output in this case will preserve all spaces and linebreaks:

  Hello, John!

  How are you today?

As you can see, in JavaScript, backticks do preserve spacing within template literals, making them useful for preserving formatting, indentation, or any other whitespaces.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.