Force JavaScript exception/error when reading an undefined object property?

Viewed 19380

I'm an experienced C++/Java programmer working in Javascript for the first time. I'm using Chrome as the browser.

I've created several Javascript classes with fields and methods. When I read an object's field that doesn't exist (due to a typo on my part), the Javascript runtime doesn't throw an error or exception. Apparently such read fields are 'undefined'. For example:

var foo = new Foo();
foo.bar = 1;
var baz = foo.Bar; // baz is now undefined

I know that I can check for equality against 'undefined' as mentioned in "Detecting an undefined object property in JavaScript", but that seems tedious since I read from object fields often in my code.

Is there any way to force an error or exception to be thrown when I read an undefined property?

And why is an exception thrown when I read an undefined variable (as opposed to undefined object property)?

7 Answers

As of now, the "right" solution to this is to use TypeScript (or another type-checking library such as Flow). Example:

const a = [1,2,3];

if (a.len !== 3) console.log("a's length is not 3!");

On JavaScript, this code will print "a's length is not 3!". The reason is that there is no such property len on arrays (remember that you get the length of an array with a.length, not a.len). Hence, a.len will return undefined and hence, the statement will essentially be equal to:

if (undefined !== 3) console.log("a's length is not 3!");

Since undefined is indeed not equal to 3, the body of the if statement will be run.

However, on TypeScript, you will get the error Property 'len' does not exist on type 'number[]' right on the "compile time" (on your editor, before you even run the code).

Reference

There is great power in consistency (like in the STL from Alexander Stepanov that Stroustrup adopted into C++). One simple reason for the inconsistent treatment of undeclared properties vs undeclared variables is probably a reflection of the thought and effort that went into evolving the different languages and another is probably the abilities of the people involved.

It also impacts the kind of applications you would entrust to any given language. You hopefully wouldn't try to write mission critical software that runs a multimillion dollar cruise liner engine management system in javascript, for example.

(Probably not a popular answer for javascript aficionados.)

Related