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 fie
Is there any way to force an error or exception to be thrown when I read an undefined property?
In short, no. You can always test for whether or not you ended up with undefined by either comparing to undefined
, like you said, or by attempting to access a second level attribute:
s = Foo()
s.bar = 1
s['Bar'] // returns undefined.
s['Bar']['Baz'] // Throws TypeError, s.Bar is undefined.
Additionally, undefined
fails in a conditional check, so you can get away with this as a shorthand for the comparison:
if (s['Bar']) {
// Something here only if s['Bar'] is set.
}
Be aware that this short hand could cause unexpected behavior if s['Bar'] was set, but was a 'Falsey' value, and you were only concerned with whether or not it came back undefined.