Nalini1998 / Project_Public

MIT License
2 stars 0 forks source link

Theory: Object coercion #559

Closed Nalini1998 closed 1 year ago

Nalini1998 commented 1 year ago

Many built-in operations that expect objects first coerce their arguments to objects. The operation can be summarized as follows:

Objects are returned as-is. undefined and null throw a TypeError. Number, String, Boolean, Symbol, BigInt primitives are wrapped into their corresponding object wrappers.

The best way to achieve the same effect in JavaScript is through the Object() constructor. Object(x) converts x to an object, and for undefined or null, it returns a plain object instead of throwing a TypeError.

Places that use object coercion include:

The object parameter of for...in loops.

The this value of Array methods.

Parameters of Object methods such as Object.keys(). Auto-boxing when a property is accessed on a primitive value, since primitives do not have properties.

The this value when calling a non-strict function. Primitives are boxed while null and undefined are replaced with the global object. Unlike conversion to primitives, the object coercion process itself is not observable in any way, since it doesn't invoke custom code like toString or valueOf methods.