Best practice for breaking up long lines in JS [closed]
Asked Answered
D

3

5

I've read several posts on this topic here, but I'm still uncertain how I should handle this issue.

In truth, the lines are in the source code much longer e.g.

console.log("html : "+"<li><a href=\""+el.find("link").text()+"\">"+el.find("title").text()+"</a>");

breaking it up in

console.log("html : "
  +"<li><a href=\""
  +el.find("link").text()
  +"\">"
  +el.find("title").text()
  +"</a>");

everything still works fine, but JSLint tells me "Bad line breaking before '+'"

What is the best practice, recommend way to keep the source human readable (production code will be minified).

Derris answered 14/7, 2014 at 9:7 Comment(1)
JSLint uses the the convention rules written by mr. Crockford. In the chapter about "Line Length" he says: "Place the break after an operator, ideally after a comma."Moolah
S
7

You must end line with +

Otherwise interpreters might treat it as the end of a line. ( thanks to Scimonster for explanation )

console.log('html: ' +
    '<li><a href="' +
    el.find('link').text() +
    '">' +
    el.find('title').text() +
    '</a>');

I recommend you to use single quotes in your JavaScript and double quotes in HTML. Then there is no need to escape double quotes, it also improves readability of your code.

Stellite answered 14/7, 2014 at 9:10 Comment(2)
I like the part about single vs double quotes in JavaScript/HTML. Will pay more attention about that from now on! ;)Satiny
It's not true that 'he must to...'. There are other options (and better in some cases) as you can see here.Hunley
P
7

Not related to the line breaking, but an alternative to concatenating strings is to use substitution strings, which sometimes makes things more manageable.

console.log('html: <li><a href="%s">%s</a>',
    el.find('link').text(),
    el.find('title').text());
Papeete answered 14/7, 2014 at 9:16 Comment(0)
S
0

What I do in such cases

var str = "html : "+"<li><a href=\"LINK\">TEXT</a>";
var str = str.replace('LINK',el.find("link").text()).replace('TEXT',el.find("title").text());
console.log(str)
Sphenoid answered 14/7, 2014 at 9:15 Comment(1)
Of course it works, but i don't think it make it more understandable.Coenzyme

© 2022 - 2024 — McMap. All rights reserved.