TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

The Dangers of += in JavaScript

11 pointsby kellysuttonalmost 14 years ago

4 comments

cfinkealmost 14 years ago
That's not a "danger" of +=; it's an explanation of why using jQuery to generate HTML is more readable than using +=.<p>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.<p>Consider this:<p><pre><code> wrappedInput += '&#60;input type="text" value="' + defaultValue + '"/&#62;'; </code></pre> If somehow defaultValue got passed in as<p><pre><code> " /&#62;&#60;script&#62;foo()&#60;/script&#62;&#60;br x=" </code></pre> , then you've just been XSS'd. If you use jQuery to set input.val(defaultValue), you're safe.
bretthopperalmost 14 years 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."<p>Or you could do the sane thing and use JS templates (handlebars, mustache, jquery tmpl, etc).
de90almost 14 years ago
This has nothing to do with 'dangers of +='.... Or am I misinterpreting this?
waffle_ssalmost 14 years ago
If you want to make it even more readable, use CoffeeScript instead of JavaScript where possible