3 ms·
The Dangers of += in JavaScript
- de90 15y agoThis has nothing to do with 'dangers of +='.... Or am I misinterpreting this?
- cfinke 15y agoThat's not a "danger" of +=; it's an explanation of why using jQuery to generate HTML is more readable than using +=. The real reason you should not be generating HTML with string concatenation is that using jQuery (or an equivalent) gives you built-in escaping for field attributes and content. Consider this: wrappedInput += '<input type="text" value="' + defaultValue + '"/>'; If somehow defaultValue got passed in as " /><script>foo()</script><br x=" , then you've just been XSS'd. If you use jQuery to set input.val(defaultValue), you're safe.
- bretthopper 15y ago"While string concatenation for building elements will do fine for small things, for larger JS projects you should use jQuery as much as possible." Or you could do the sane thing and use JS templates (handlebars, mustache, jquery tmpl, etc).
- waffle_ss 15y agoIf you want to make it even more readable, use CoffeeScript instead of JavaScript where possible