00 Votes

JavaScript: Line Break - What is the difference between \ and \n?

Question by HomeMan | 2012-08-06 at 21:03

Apparently, in JavaScript, both \ and \n can be used as a new line. What is exactly the difference between these two types of line breaks?

ReplyPositiveNegative
2Best Answer2 Votes

The difference between \ and \n can be illustrated well with the following example:

alert("1 \n 2 \
3 \n 4 \
5 \n 6");

// Output:
// "1
//  2 3
//  4 5
//  6"

The line break \ is only stated in the code and is only visible to the programmer. It can be used, whenever you have a very long string in your code, that span over multiple lines. A string over multiple lines, you can specify with \ at the end of the line as it is shown in the example. Otherwise, JavaScript only accepts strings written in one line of code.

In contrast \n is the specificaton of a newline, which can also be seen by the user in the output later. For this kind of line break, the code do not have to wrap and so you can write multiple line strings in one line of JavaScript code.
2012-08-07 at 23:51

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.