Hacker News new | ask | show | jobs
by timdown 6026 days ago
For that specific case, the more verbose version is definitely better, since the undefined property of the global object can be altered. For example, this silently redefines it for the whole page:

if (undefined = someVar) {...}

The typeof check cannot be broken in this way.

1 comments

Sorry, that one wasn't the most effective example. 'undefined' is read-only in the ES3.1 specification and at some point you'll start to see code like the above failing.

15.1.1.3 undefined The value of undefined is undefined (see 8.1). This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.

It's true that it can be broken today by unintentional assignment at the global scope, but you're basically skating on thin ice as soon as you redefine undefined or one of the many built-in global object types or global mutable values anyways (Array, Element, Object, NaN for example). Ditto for adding anything to Object.prototype.

I wouldn't blame a framework for wanting to place at least some burden on the user to follow a set of basic guidelines to ensure the library functions correctly. Ideally you'd ship your development-time, unminified version of the library with a bunch of startup-time assertions to ensure that the user isn't accidentally walking over core JS objects.

Alternatively, you could workaround the mutable nature of some of the globals by defining your own in-scope. When these values are eventually made read-only, these assignments should become no-ops:

var undefined = void 0; var NaN = 0/0; var Infinity = 1/0;

This is comment is rambling a bit, but I think I can justify the position that at least some of the recommended practices of the c.l.j folk are wordy, unnecessary and out-dated.