This post will discuss how to add a new line in a JavaScript or a HTML document.

A newline is a special character that moves the cursor to the next line. There are several ways to add a newline in JavaScript, depending on where we want to print it. Here are some of the methods we can use:

1. Using \n escape sequence

We can insert a newline character in a string literal by using the \n escape sequence. The \n character is called an escape sequence, which means it has a special meaning and is not printed as a normal character. We can use this when we want to add a newline in the console, in an alert box, or in any other place that accepts a string. Here’s an example of how we can achieve this:

Download  Run Code

 
As demonstrated, to insert a new line in JavaScript, we need to use the special character \n inside a string. There are other escape sequences in JavaScript, such as \t for a tab, \r for a carriage return, and \" for a double quote.

2. Using <br> HTML tag

However, if we are writing HTML code with JavaScript, the \n character will not create a visible line break in the browser. Instead, we need to use the HTML tag <br> to insert a line break. For example, if we want to write "Hello" and "World" on two separate lines in an HTML document, we can do this:

Download Code

 
The <br> tag is an HTML element that tells the browser to start a new line. There are other HTML elements that can create line breaks, such as <p> for paragraphs, <h1> for headings, and <li> for list items. We can directly insert a line break in an HTML document by using the <br> HTML tag. Here’s an example of how we can achieve this:

Download Code

3. Using CSS property

Finally, we can use the CSS property white-space: pre to preserve the whitespace characters in our text, such as spaces, tabs, and newlines. We can this property on an HTML element to make it display the text as it is written in the source code, without collapsing or ignoring the whitespace characters. For example:

Download Code

That’s all about adding a new line in a JavaScript or a HTML document.