JavaScript Coding Conventions

56 views
Skip to first unread message

Caleb Morse

unread,
Mar 28, 2013, 3:52:35 PM3/28/13
to cesiu...@googlegroups.com
Do you guys have a rule against using JavaScript short circuit evaluation?

Basically instead of writing:
var interval = externalData.interval;
if (typeof interval !== 'undefined') {
    interval = TimeInterval.fromIso8601(interval);
}

you would do:
var interval = externalData.interval || TimeInterval.fromIso8601(interval);

This is used extensively in the jQuery library, so it has broad browser support.

Scott Hunter

unread,
Mar 28, 2013, 6:02:57 PM3/28/13
to cesiu...@googlegroups.com
We generally use typeof x === 'undefined' everywhere for two reasons:

1. The coercion to boolean in a || b uses "truthiness", so if a is 0, or empty string, or any of the other miscellaneous values that are considered falsy, you can end up using the default value unintentionally.  We've had bugs in the past caused by this, so rather than worry about it on a case-by-case basis, the typeof check always works the same way.
2. The typeof check actually ends up being faster than the boolean coercion, surprisingly.  Even though the code makes you think it's going to get the type of x as a string, then do a string comparison with 'undefined', it actually doesn't do any of that.  Since even in the wild west of JavaScript, scripts can't influence how typeof works, or interfere with string literals, or impact reference equality checks, the VM can easily collapse it down to a single instruction.


--
You received this message because you are subscribed to the Google Groups "cesium-dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cesium-dev+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages