How To Break Line In Javascript

When working with JavaScript, it is often necessary to break lines in order to create a more readable and
structured output. In this blog post, we will explore different ways to insert line breaks in JavaScript so that
you can format your console logs, alerts, and even HTML outputs more effectively.

Using the newline character (n)

The most common way to break a line in JavaScript is by using the newline character n. This
special character is recognized by most systems as a command to start a new line. Here’s an example of how to
use this character in a string:

    const message = 'Hello, world!nHave a great day!';

When you run this code, you will see the following output in the console:

Hello, world!
Have a great day!

Breaking lines in HTML output

If you want to break lines in an HTML document, you should use the <br> tag instead of the
newline character. The <br> tag is an HTML element that represents a line break in text.
Here’s an example of how to use this tag when modifying the contents of an HTML element using JavaScript:

    const message = 'Hello, world!<br>Have a great day!';
    document.getElementById('example').innerHTML = message;

In this example, the output will be displayed on the webpage with a line break between “Hello, world!” and
“Have a great day!”.

Using template literals

Another way to break lines in JavaScript is by using template literals (also known as
template strings). Template literals are a modern way of working with strings in JavaScript, introduced in ES6.
They allow you to write multiline strings without using the newline character. To define a template literal,
use backticks (`) instead of quotes. Here’s an example:

    const message = `Hello, world!
Have a great day!`;

This code will produce the same output as our first example. Template literals also support interpolation,
which means you can embed expressions in the string without having to concatenate them manually. This can make
your code even more readable:

    const name = 'John';
    const message = `Hello, ${name}!
Have a great day!`;

This code will output the following message in the console:

Hello, John!
Have a great day!


In this blog post, we have explored different ways to break lines in JavaScript, including the newline character
n, HTML’s <br> tag, and template literals. Choose the method that best
fits your specific use case and enjoy writing more readable and well-formatted JavaScript code.