Interesting Javascript Tips

Despite being a Javascript user for years, there were some things I still didn’t know.
Here are some of the interesting points I found from Ben Cherry’s presentation


names are always hoisted to the top of their scope
and always initialized to undefined


var foo = 1;
(function () {
alert(foo); // undefined
var foo = 2;
}());
alert(foo); // 1


var foo = 1;
(function () {
alert(foo); // alerts "1"
// in the previous example foo is hoisted to the top as "undefined"
}());
alert(foo); // 1


CSS expressions are evaluated right-to-left!


#foo div a {/* ... */}

this starts by looking at every
then it looks for those whose parent is

then it checks to see if its parent is #foo


parseInt needs radix!

parseInt("123"); // 123
parseInt("10"); // 10
parseInt("010"); // 8 -> WTF?

// with a radix
parseInt("010", 10); // 10 -> crisis averted!

never forget your radix


avoid inline scripts
these cannot be cached or minified
only put dynamic values here


you can detach sub-trees


var elem = $("#myelem"),
parent = elem.parent();

elem.detach();
// ... muck with elem and sub-elements ...
parent.append(elem);

.detach() is new in jQuery 1.4


how to make BC.util?


BC.util = (function (BC) {
var util = {},
foo; // private variable

// public
util.someFunction = function () {};

// private
function someOther() {}

return util;
}(BC));


loops


// slow method
var i;
for (i = 0; i < someArray.length; i += 1) {
// ...
}
// faster
var i, l;
for (i = 0, l = someArray.length; i < l; i += 1) {
// ...
}

Popularity: 4% [?]

Comments are closed.