I've recently learned that if I try to write to a JavaScript property that has get
but no set
, it is ignored in "sloppy mode", but is an error in strict mode.
OTOH, if I try to read from a set
-only property, this returns undefined
in both modes. Is there a reason why this is not also an error in strict mode?
It is probably because it's common practice to test if an object obj
's property prop
has a value by doing
if (obj.prop) { ...
or
if (obj.prop !== undefined) { ...
One of the objectives of strict mode (as stated on MDN) is:
- Eliminates some JavaScript silent errors by changing them to throw errors.
When a programmer tries to set an unsettable property, the intention of the programmer is clear, i.e. they want to set a property. So the engine can warn you by throwing an error.
But when you do obj.prop
, the intention isn't very clear. As doing obj.kljasfbbsdbgjksb
(a key that is not defined) is also perfectly legal.
Is the programmer trying to get the value, or simply inspect the nature of obj.prop
by doing typeof obj.prop
, obj.prop === undefined
, etc.