Express, EJS, challenge with testing for undefined-Collection of common programming errors

Because the concept of “undefined” is different than the state of a variable being defined in the JavaScript language. The reasons for this are understandable but the effects can be confusing, especially regarding variable names vs object properties.

You have demonstrated how trying to access an undefined variable will throw an exception. Don’t confuse this state (a variable is not defined) with the “undefined” type:

if (bogusVariable) { // throws ReferenceError: bogusVariable is not defined.
typeof(bogusVariable); // => undefined - wow, that's confusing.

However, properties of objects which are not defined can be tested safely:

var x = {}; // an object
x.foo; // => undefined - since "x" has no property "foo".
typeof(x.foo); // => undefined
if (!x.foo) { /* true */ }

You could take advantage of this property by noting that all variables are actually properties of the “global” object (either “global” or “window”, in web browsers).

bogus; // => ReferenceError: bogus is not defined.
global.bogus; // => undefined (on node/rhino)
window.bogus; // => undefined (on web browsers)

So you might be able to write your EJS code as such:


  


Yes, it’s confusing, as are many parts of the JavaScript language.

Originally posted 2013-11-09 21:08:06.