By assuming that anything passing the first check will also pass the second one, your if
statement will not throw an error. Even without a constructor
property, it will still support the second check (returning
undefined</code) or be temporarily promoted as an object if not designated as such. However, this approach may fail when dealing with arrays from different windows, as highlighted by <a href="https://stackoverflow.com/questions/41598160/is-it-safe-in-javascript-to-assume-the-existence-of-constructor-property-on-va/41598207#comment70399247_41598160">dandavis</a>.</p>
<p>It's important to note that while not every object has a <code>constructor
property, you won't receive an error even if it doesn't exist; instead, you'll get
undefined
. Objects without a
constructor
property can be created using methods like
var obj = Object.create(null);
or employing an object with a prototype of
null
.
However, I wouldn't recommend relying on this method to determine whether something is an array. In modern environments, it's better to use Array.isArray
; for older environments, consider shimming/polyfilling it. This way, you ensure compatibility with arrays from various sources.