In JavaScript, Arrays are Object, which is why we were told to never use the in
operator on arrays because it can expose other attributes of the array object that are not meant to be exposed. The of
operator was introduced so the arrays would have a membership operator that doesnât cross the line on Array objects that in
does.
of
has not been around for that long, if youâre my age. It may have always existed if one started coding in 2005 or later. The key word is membership. Both in
and of
refer directly to the values referenced, not their index position in the array.
Bottom line, where in
is used to test membership, a special purpose operator, it can also (more typically) be used to work with for
in iteration of an objectâs key set. Given the dual purpose utility, it can also be used in while
loops:
x = 'somekey'
while (x in obj) {
// loop for some time until some action removes the key/value
}
Thatâs just theory so donât look for practical value, only demonstrative.
When thinking of in
or of
weâre not considering their position, which in the case of in
doesnât matter or have any bearing since there is no discernable position in an object. of
in a sense is wired the same way. We need to poll the array for the index of a value, and then can only rely on it to give us the first position since arrays can have multiple repeated values. Objects cannot have any repeating keys.
It really only becomes important to know a valueâs position if we wish to mutate it. A value cannot be mutated in an of
loop. Sure we have the value in memory (the iteration variable) but we have no direct binding to its location in memory, only its occurrence within the list of items.
Say we have a list of fruits, unordered in an array. We wish to find where apple
is positioned in the array, notwithstanding there may be more than one âappleâ. We want to change that to âbanana appleâ.
fruits[fruits.indexOf('apple')] = 'banana apple'
Eg.
> fruits = ['banana', 'pear', 'orange', 'apple', 'grapefruit']
<- (5) ['banana', 'pear', 'orange', 'apple', 'grapefruit']
> fruits[fruits.indexOf('apple')] = 'banana apple'
<- 'banana apple'
> fruits
<- (5) ['banana', 'pear', 'orange', 'banana apple', 'grapefruit']
>
Fun fact
We in the Prairies used to refer to âGolden Deliciousâ by that moniker. I didnât just make it up.