While chatting with a bud the other week, we started chatting about JS best practices. Normal conversation, you know. I explained that one of the best things you can do is to wrap everything, if using jQuery, in a $(). “But for why?” my friend questioned. The answer is a little complicated and very opinionated.

When dynamically building HTML snippets in JavaScript, many ways are possible, each with their upsides and downsides. I’m here today to argue though, that my way is the best.

For examples purposes, let’s take a look at simple method that could be called a bunch that wraps an <input> with a default value inside of a <div>.

http://gist.github.com/1152559.js?file=butForWhyPlusEquals.js

Boom. Easy as pie. This makes exactly what we want and it does it pretty fast. If we want to be even faster:

http://gist.github.com/1152600.js?file=joinThoseBros.js

Double boom. Easier and faster. But neither of these solutions are very readable. And more important, they don’t fail when they should. If you mess up one single-quote or double-quote, you may not see the problem for a while or may have to hack something together down the line. Chances are, you’re already using jQuery on your page. If you’re using it, you should lean on it as hard as you possibly can for your first pass.

https://gist.github.com/1152617.js?file=LetUsAppend.js

Oh my, what have I done? I have added lines of code and made it slower! Why would one voluntarily do such a thing? Ostensibly, my code is more readable. I will also see problems sooner since jQuery has a tendency to fail harder, sooner. That alone is worth the performance losses we may see.

While string concatenation for building elements will do fine for small things, for larger JS projects you should use jQuery as much as possible. Coworkers will be able to pick up what you’re doing earlier. As your code base grows, keeping the single- and double-quotes will give you and your team headaches. It can be later optimized and commented accordingly if it’s a pain point in profiling.

We should be making the tough to decision to write slower but safer JavaScript.

(Also, nevermind that I ignored the jQuery.wrap() method. Just trying to make a point.)

  1. gorczycajexp593398 reblogged this from kellysutton
  2. symboltoproc reblogged this from kellysutton
  3. shevralay reblogged this from kellysutton and added:
    me snort diet coke out of
  4. jonprins reblogged this from allang
  5. mcdavis said: Cancel that, I just realized that when in the dashboard, the embeds just show as a url for the embed script instead of a url for the actual gist page.
  6. kellysutton posted this