Add New Line in JavaScript

Discover many methods to make a line break in your JavaScript code.

In JavaScript, there are several ways to make a line break. Here is what you will discover in this article:

  • newline character in JavaScript
  • templates literals in JavaScript
  • line break tag in HTML (can be helpful if you generate your HTML with JS)

Let's have a look at them!

Add a new line in JavaScript using an escape sequence (the new line character)

The first way to make a line break is to use an escape sequence. Escape sequences are sequences of characters with a particular role depending on where they are placed in a string.

There are many of them, but we are interested in the new line character representing a line break (\n).

We can use it in our code, as in the example below. When JavaScript interprets this sequence, it will replace it with a new line.

console.log('Hello World!\nHow are you?')

/*
Hello World!
How are you?
*/

Add a JavaScript new line using template literals

Another way to create a new line in JavaScript is to use a template literal. A template literal is a string that allows integrating expressions like multi-line strings or interpolation. But, what we are interested in here is the interpretation of the line break. The template litteral is characterized by the magic quotes (``).

console.log(`Hello World!
How are you?`)

/*
Hello World!
How are you?
*/

Add a new line in HTML using a line break tag (<br>)

The last way to add a newline in JavaScript is to use the <br> HTML tag. You can use it in an HTML string, and like the new line character \n, the <br> tag will be interpreted in the HTML code as a line break.

In JavaScript, you can use document.write to write in your HTML DOM.

document.write('Hello World!<br/>How are you?')

Here is an example of output that you can generate with the above instruction:

<body>
  Hello World!
  <br />
  How are you?
</body>

➡️ If you want to follow all my latest content about web development, I invite you to follow me on LinkedIn. 🗞

Learn to code with simple and concrete examples.

English / Français