The in operator

The in operator will return true if a property can be found in an object:

'foo' in { foo: 123 }; // => true

The left-side operand will be coerced to its primitive representation, which, if not Symbol, will be coerced to String. Here, we can see how a left-side operand that is Array will be coerced into a comma-separated serialization of its contents (the native and default way that arrays are coerced to primitives, thanks to Array.prototype.toString):

const object = {
'Array,coerced,into,String': 123
};

['Array', 'coerced', 'into', 'String'] in object; // => true

All seemingly numeric property names in JavaScript are stored as strings, so accessing someArray[0] is equal to someArray["0"], and therefore enquiring as to whether an object has a numeric property with in will also consider both 0 and "0" equally:

'0' in [1]; // => true
0 in { '0': 'foo' }; // => true

When establishing whether a property is in a given object, the in operator will traverse the entire [[Prototype]] chain, hence returning true for all accessible methods and properties at all levels of the chain:

'map' in [];     // => true
'forEach' in []; // => true
'concat' in []; // => true

This means that if you're looking to distinguish between the concepts of having a property and having a property on itself, you should instead use hasOwnProperty, a method inherited from Object.prototype that will only check the object itself:

['wow'].hasOwnProperty('map'); // => false
['wow'].hasOwnProperty(0); // => true
['wow'].hasOwnProperty('0'); // => true

On the whole, it is best to only use in if you're confident that there are no collisions with the property names you expect to use and properties provided by the object's [[Prototype]] chain. Even if you're just using plain objects, you still need to worry about the native prototype. If it's been modified in any way (by a utility library, for example), then you can no longer have a high level of trust in the results of your in operations and should hence use hasOwnProperty.

In older library code, you may even find code that chooses not to rely on hasOwnProperty on the object of inquiry, fearing that it may have been overridden. Instead, it'll opt for using the Object.prototype.hasOwnProperty method directly and calls it with that object as its execution context:

function cautiousHasOwnProperty(object, property) {
return Object.prototype.hasOwnProperty.call(object, property);
}

This is likely overly-cautious though. It's safe enough in most code bases and environments to trust and use the inherited hasOwnProperty. The in operator as well, if you've considered the risks, is usually safe enough to use.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.74.54