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:
Let's have a look at them!
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?
*/
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?
*/
<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>