Advanced Javascript Tricks
Recently I’ve watched a few presentations about Javascript on YouTube and learned some tricks I want to share:
1. A Big Closure Around your Code
2. Faster jQuery Selection
3. JavaScript’s odd Boolean Comparison Operators
1. A Big Closure Around your Code
When you’re writing a more complex piece of code, you’re likely to have the need for private variables and prevention of code collision (e.g. with frameworks). The following is a very nice pattern that offers not only both mentioned things, but will also speed up your code a little bit and make sure, that undefined really is what it seems to be, NOT defined:
var undefined = "foo"; // This is perfectly legit in today's JS, and now: undefined === "foo"; // Which is just completely wrong and potentially dangerous (function(window, document, undefined){ var test; // Local scope = Not accessible from outside = Private var getTest = function(){ return test; // Accesses the local scope variable } document.getFooByBar(); // This accesses the local scope variables "document" window.doSomething(); // and "window", instead of the ones in global scope, // which makes access a bit faster test === undefined; // We access the local scope variable "undefined" // here, which is in fact undefined, and are thus // preventing bad things from happening })(window, document);
Wrap your code in a closure-function like shown when ever possible. This will also benefit code-minification, since all the local variables (including window and document) can and will be minified.
Many jQuery Plugins use this method to pass in the framework root, too:
(function($){ $.fn.foo = ... })($);
2. Faster jQuery Selection
While we’re at it: If you‘re using jQuery in your application/site and you want to select elements that are descendants of an element that has a DOM Id given, you might be using one of theese queries:
$("#element_id foo.bar"); $("#element_id > foo.bar");
And actually, this is not the best way to perform this selection. The following version is more structured (imho) and a bit faster – not a lot, but if you’re running this a thousand times, you’ll notice a good difference:
$("#element_id").find("foo.bar"); $("#element_id").children("foo.bar");
This version selects an element by it’s DOM Id and then searches in it’s descendants/children. Why is this faster? Because jQuery can parse the DOM id-selector directly (using the document.getElementById() function) instead of passing the whole query into Sizzle (which is the CSS-selection engine jQuery uses) and thus being faster, because Sizzle only has to parse the find() part within the selected element.
3. JavaScript’s odd Boolean Comparison Operators
In case you didn’t know: JavaScript won’t evaluate the following statement as you might expect it from other languages:
var test = (false || 4 || "foo"); // What we expect: test === true; // Result: test === true; // FALSE test === 4; // TRUE
First: This is awesome! Second: Why is that? Since JavaScript is a typeless language, everything that isn’t an empty string, a zero, false, null/NaN or undefined will be equal (==) to true. That’s why there is no need for JS to parse comparison operator statements into booleans, but rather have them return the original value.
This is very nice, because you can do the following to create an easy way to have default values:
var classNames = { "test": "testClass", "odd": "colorOdd", "_default_": "normal" }; var foo = "notExistingKeyName"; var className = classNames[foo] || classNames._default_; // undefined || "normal" // Result: className === classNames._default_ === "normal";
In the case that the classNames object had a key called notExistingKeyName, that value would have been returned. But the script, as is, will fall back and return the value of the object’s _default_ key.
Note how that won’t affect the function of those operators in any way you’re used to:
var foo = false; var bar = 4; var compare = (foo || bar); // This will turn into: compare === bar === 4; // And thus: compare == true; // If you need a boolean, use a double negation var bool = !!(foo || bar); bool !== 4; boll === true;
The AND operator will return the last value, if all values are equal to true, or the first value that is equal to false:
var foo = null; var bar = 4; var john = "doe"; var a = (foo && bar && john); a === null; a == false; var b = (bar && foo); b === foo; // This will also work with undefined: var undef; var c = (undef && bar); var c === undefined;



