The 'in' operator of JavaScript
JavaScript is one of the weirdest programming languages both syntactically and by use case. JavaScript is widely used to create fullstack websites, cross-platform mobile applications and even desktop applications. Inspite of it wide usage, JavaScript with its different features can make the developer go nuts. One such thing is the 'in' operator.
In other programming languages like Python, the 'in' keyword directly represents its semantic meaning, i.e., usage of 'in' keyword checks for the presence of an item in an iterable. Whereas in Javascript, the 'in' operator checks for the presence of a particular property in an object. Doesn't sound strange right? The peculiarity becomes even more evident when using 'in' operator with arrays.
'in' operator with JavaScript objects
As mentioned earlier, the 'in' operator is used to check for the presence of a property in a JavaScript object.
For example,
const shoppingCart = { 'apple': 1, 'banana': 5, 'pears': 3 }
console.log( 'apple' in shoppingCart ) //Output: true
The above code is said to return true. But what if it was used in an array?
'in' operator with JavaScript arrays
const shoppingCart = [ 'apple', 'banana', 'pears' ]
console.log( 'apple' in shoppingCart ) //Output: false
Semantically, it should return true instead, it returns false. Why is this happening ? Behind the hood, Javascript's 'in' operator checks for the existence of an index and so the unexpected answer. Let's see something more weird.
const shoppingCart = [ 'apple', 'banana', 'pears' ]
console.log( '1' in shoppingCart ) //Output: true
The above snippet returns true, because the 'in' operator checks for the presence of an element at the '1'st index instead of checking for the presence of an actual '1' in the array. Let's see what happens under the hood in JavaScript arrays.
Behind the scenes of JavaScript arrays
Arrays are interpreted as objects by JavaScript. The _shoppingCart _array defined above is interpreted by JavaScript as follows:
const shoppingCart = { 0: 'apple', 1: 'banana', 2: 'pears', length: 3}
This clearly explains the behaviour of the 'in' operator. So, it checks whether the '1'st index is actually not undefined. If it does, it returns true else false. But why do someone dare to use it with the JavaScript arrays? The answer is, 'in' operator with the JavaScript arrays checks for the presence of a particular index. If you wish to learn more about the 'in' operator, check out the official docs on MDN:
Top comments (2)
I ran into bugs while I was trying to use this in operator in one of my projects. Even though its not been a while since I've started my Js course, this helped me revise the specific use case of the 'in' operator.
This means a lot to me. Thanks..!