How to make a new line in javascript?

Software
AffiliatePal is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Listen

Introduction

In JavaScript, creating a new line is a common requirement when working with strings or displaying text in a specific format. This article will explore different methods to make a new line in JavaScript, allowing you to add line breaks and improve the readability of your code or output.

Using the Line Break Character

The simplest way to make a new line in JavaScript is by using the line break character, represented by ‘n’. You can include this character within a string to create a line break wherever you need it. For example:

“`javascript
let message = “Hello,nWorld!”;
console.log(message);
“`

This will output:

“`
Hello,
World!
“`

By adding ‘n’ within the string, the console.log() function interprets it as a line break and displays the text on separate lines.

Using Template Literals

Template literals, introduced in ECMAScript 6, provide a more flexible way to create strings in JavaScript. They allow for multiline strings by using backticks (`) instead of single or double quotes. To create a new line within a template literal, you can simply press Enter. Here’s an example:

“`javascript
let message = `Hello,
World!`;
console.log(message);
“`

This will produce the same output as before:

“`
Hello,
World!
“`

Template literals automatically interpret new lines within the string, making it easier to write and read multiline text.

Using the Concatenation Operator

Another approach to creating a new line in JavaScript is by concatenating strings using the ‘+’ operator. You can concatenate a line break character (‘n’) with the strings you want to join. Here’s an example:

“`javascript
let message = “Hello,” + ‘n’ + “World!”;
console.log(message);
“`

This will also display:

“`
Hello,
World!
“`

By concatenating the line break character between the two strings, you achieve the desired line break effect.

Using the String.fromCharCode() Method

The String.fromCharCode() method allows you to create a string from a sequence of Unicode values. By passing the Unicode value for a line break (10) as an argument, you can generate a new line within a string. Here’s an example:

“`javascript
let message = “Hello,” + String.fromCharCode(10) + “World!”;
console.log(message);
“`

This will produce the same output as the previous examples:

“`
Hello,
World!
“`

Using String.fromCharCode(10) adds a line break to the string, resulting in the desired formatting.

Conclusion

In JavaScript, there are several methods to make a new line within a string. You can use the line break character ‘n’, template literals, the concatenation operator, or the String.fromCharCode() method. Choose the method that best suits your needs and enhances the readability of your code or output.

References

– developer.mozilla.org
– www.w3schools.com