JS Tips & Tricks, Secrets of the JavaScript Ninja and JavaScript: The Good Parts will cover almost everything you need to know about JavaScript. Still, there are a few tricks that I use almost every day that I feel are often underrated:
  • && and || aren't your father's boolean operators. Thanks to JavaScript's notion of truth (anything but false, null, 0, undefined and the empty string), they don't have to return boolean value, and will not unless you coerce it into one with !!. That means you can use them inline as part of assignments and in parameter lists. e.g,
    function(someParam) {
    // provide a default value
    someParam = someParam || {};
    // ...

    // guard against null objects
    var count = foo && foo.count || 0; // if foo is null, count == 0, else foo.count
  • function scope:
    // ...
    The key here is that you're taking a global/wider scoped variable and making it a local variable, which allows you to rename/replace the original variable with little to no impact to your code. For example, suppose you need to use 2 versions of jQuery in your page. If you have the good sense to wrap all of your scripts in a function, you can include jQuery version A, then include your scripts that need version A, then include jQuery version B and your other scripts. Or if you wrote all of your scripts using $ as a reference to jQuery and then wanted to use Prototype in the same page.

    The other nice thing about wrapping your scripts is that any vars and function your define wont bleed into the window scope unless you specifically assign them to window. e.g., window.GLOBAL_FOO = 123;

Sorry for the short post. I have some more code heavy stuff I think I'm working on for next time, I promise.

No comments: