Search code examples
javascripthtmlline-breaks

what's the different between <br> and \n as line break


I just finished a very simple assignment from my class. The part of the wrong code of script I wrote is like this:

alert("The circumference of a circle with this radius is " + circum + 
    "<br>" + "The area of a circle with this radius is " + area + "\n" + 
    "The surface area of a sphere with this radius is " + surarea + "\n" + 
    "The volume of a sphere with this radius is " + volume + "\n");

I have tried both <br> and \n in this part of code, and I am pretty sure that other parts are all right since I have tested them.

I was just wondering why the <br> doesn't work for me on my program. The example that the teacher gave us seems working fine. But he also told us that <br> should be used in HTML while \n is used in JS.

Thank you very much.


Solution

  • \n is a linebreak character. It is interpreted like that by the JS compiler. The HTML parsers on the other hand treat it as a normal string.

    <br> in html is a tag to introduce a line break. In JS strings, this is treated as a normal string.