Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Why does false.something evaluate to undefined?

Tags:

javascript

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?

like image 218
Sven Avatar asked Oct 28 '25 13:10

Sven


1 Answers

When properties are accessed on primitives, JavaScript auto-boxes the value into a wrapper object and accesses the property on that object instead.

https://developer.mozilla.org/en-US/docs/Glossary/Primitive

false and true are implicitly converted to Boolean objects here, i.e. you are reading nonExistingProperty from a Boolean instead of the boolean primitive.

like image 162
idmean Avatar answered Oct 30 '25 05:10

idmean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!