skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. Undefined tells that the property is undefined.

    x =  {}
    console.log(x.undefinedProperty1) // undefined
    x.undefinedProperty1 = 123
    console.log(x.undefinedProperty1) // 123
    

    An error would appear if you tried to call a function that was not defined

    x.undefinedProperty1() // error: undefinedProperty1 is not a function
    
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
  4. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search