While learning about the optional chaining operator I experimented a bit and found out that these two evaluate to undefined:
false.nonExistingProperty // undefined
true.nonExistingProperty // undefined
But why is that so? Shouldn’t this throw an error?
4
Answers
https://developer.mozilla.org/en-US/docs/Glossary/Primitive
false
andtrue
are implicitly converted toBoolean
objects here, i.e. you are readingnonExistingProperty
from aBoolean
instead of the boolean primitive.Undefined tells that the property is undefined.
An error would appear if you tried to call a function that was not defined
In JavaScript, when you attempt to access a property on a primitive value (such as true or false), the language will perform "boxing", which temporarily converts the primitive value to its object wrapper (a Boolean object in this case) to allow property access. Once the property access is complete, the temporary object wrapper is discarded.
In your examples:
false.nonExistingProperty accesses a property on the false Boolean value. JavaScript temporarily boxes false to a Boolean object, which does not have the property nonExistingProperty. Since the property does not exist, the result is undefined.
Similarly, true.nonExistingProperty accesses a property on the true Boolean value. JavaScript boxes true to a Boolean object, which also does not have the property nonExistingProperty, resulting in undefined.
This behavior is part of JavaScript’s coercion and type conversion rules. JavaScript does not throw an error when accessing a non-existent property on a primitive value, and instead, it returns undefined. This behavior is designed to prevent runtime errors and make JavaScript more forgiving and flexible.
In JavaScript, when you try to access a property on a primitive value like false, JavaScript internally coerces the primitive value to an object using the concept of object wrappers. These object wrappers are temporary objects created around primitive values to allow you to access properties and methods on them.
When you try to access a non-existing property on false like false.nonExistingProperty, JavaScript creates an object wrapper around the false primitive value. However, since there is no property named nonExistingProperty on this object, the result of the expression is undefined