Because you can never know too many micro-optimizations...
In JavaScript, when you need to know if a property is present on an object, you have a couple of options. For a long time, I've used the following idiom:
if ('undefined' !== typeof obj['prop']) { /* do something */ }
Recently, I came upon some code using the following:
if ('prop' in obj) { /* do something */ }
I like the clarity of the syntax. Which is faster? Let's find out!
function eq_(obj, prop, iters) {
var start, result;
start = new Date;
do {
result = ('undefined' !== typeof obj[prop]);
} while (--iters);
$('#duration-eq').html(new Date - start);
$('#result-eq').html(result.toString());
}
Result: ---
Duration: ---
function in_(obj, prop, iters) {
var start, result;
start = new Date;
do {
result = (prop in obj);
} while (--iters);
$('#duration-in').html(new Date - start);
$('#result-in').html(result.toString());
}
Result: ---
Duration: ---