For now I'm writing a complex of laboratory works about coding in JavaScript. I know that there is a construction like
if ('field' in object) {
/* Do something with object.field */
}
to be used to determine that a variable called field
really exists in object
even if it equals to undefined.
And my Firefox Developer Edition 44 is able to determine if there is a field in an array like this:
if (0 in array) {
/* Do something with first element */
}
The question: is this method legal? Is it a part of a living standard or not?
What it is supposed to do:
Let q be an array with such elements:
[ 5, <1 empty slot>, undefined, 5 ]
Then:
0 in q
,2 in q
,3 in q
equals totrue
;1 in q
equals tofalse
.
Sure. The
in
operator checks to see if a property exists in the object (directly, or via the prototype chain). The left-hand operand is the name of the property, the right-hand operand is the object to check. If the left-hand operand isn't a string orSymbol
, it's coerced to a string. This is all completely within the specification:The
in
operator (scroll down to RelationalExpression : RelationalExpression in ShiftExpression)The abstract
ToPropertyKey
operationThe abstract
HasProperty
operationJavaScript's untyped arrays are objects (and not really arrays, although engines optimize that when they can). Array indexes are property names (and technically strings, though engines optimize that when they can). So you can use
in
to check if an array contains a property by using an "array index" within
and the array. (You can also usehasOwnProperty
:theArray.hasOwnProperty(0)
, but it's slower with arrays on modern engines.)Yes, that's perfectly valid: