Being obsessed with neatness in Javascript lately, I was curious about whether there is some type of common practice about how to deal with lines that span over 80 cols due to string length. With innerHTML I can mark line breaks with a backslash and indentation spaces won’t show up in the content of the element, but that doesn’t seem to go for eg. console.log().
Are there any conventions for this or should I just learn to live with lines longer than 80 cols? 🙂
There’s no universal convention. With modern high-res monitors you can easily fit 160 columns and still have room for IDE toolbars without needing to scroll, so I wouldn’t be concerned about sticking to 80 columns.
Some people go out of their way to never have any line of code go past n columns, where n might be 80, or 160, or some other arbitrary number based on what fits for their preferred font and screen resolution. Some people I work with don’t care and have lines that go way off to the right regardless of whether it is due to a long string or a function with lots of parameters or whatever.
I try to avoid any horizontal scrolling but I don’t obsess about it so if I have a string constant that is particularly long I will probably put it all on one line. If I have a string that is built up by concatenating constants and variables I will split it over several lines, because that statement will already have several
+operators that are a natural place to add line breaks. If I have a function with lots of parameters, more than would fit without scrolling, I will put each parameter on a newline. For an if statement with a lot of conditions I’d probably break that over several lines.Regarding what you mentioned about
innerHTMLversusconsole.log(): if you break a string constant across lines in your source code by including a backslash and newline then any indenting spaces you put on the second line will become part of the string:If you use that string for
innerHTMLthe spaces will be treated the same as spaces in your HTML source, i.e., the browser will display it with multiple spaces compressed down to a single space. But for any other uses of the string in your code includingconsole.log()the space characters will all be included.If horizontal scrolling really bothers you and you have a long string the following method lets you have indenting without extra spaces in the string: