The in operator
The in operator in JavaScript is used to check
whether a given property exists in an object or an index exists in an array.
This is one of the basic, but often misunderstood, operators. Let's go through it in detail.
Syntax
propName in objectWhere:
propNameis a string (or an expression coerced to a string),objectis an object, array, or another structure with keys.
Example with an object
const user = {
name: 'Tim',
age: 25
};
console.log('name' in user); // true
console.log('age' in user); // true
console.log('email' in user); // falseThe
inoperator returnstrueif the property exists in the object (even if its value isundefined).
Features
Even if the property's value is undefined, in will still return true:
const obj = { a: undefined };
console.log('a' in obj); // true
console.log(obj.a === undefined); // trueIn other words,
inchecks for the presence of a key, not its value.
Example with an array
const arr = ['a', 'b', 'c'];
console.log(0 in arr); // true - index 0 exists
console.log(2 in arr); // true - index 2 exists
console.log(3 in arr); // false - no such indexJS treats array indexes as properties:
arr[0]is equivalent toarr['0'].
Example with inheritance (via the prototype)
The in operator checks not only own properties,
but also ones inherited through the prototype.
const person = { name: 'Tim' };
console.log('toString' in person); // true, because it's inherited from Object.prototypeTo check only own properties, use
obj.hasOwnProperty('key'):javascriptperson.hasOwnProperty('toString'); // false person.hasOwnProperty('name'); // true
Example with a class
class User {
constructor() {
this.name = 'Alex';
}
}
User.prototype.age = 25;
const u = new User();
console.log('name' in u); // true (an own property)
console.log('age' in u); // true (inherited from the prototype)Error when used with a non-object
If the right-hand side is not an object (and cannot be coerced to one), JS will throw an error:
'length' in null; // TypeError
'length' in undefined; // TypeErrorSo before checking, make sure the variable is not
nullorundefined.
Summary
| Checks | The presence of a key (property / index) |
|---|---|
| Works with | Objects, arrays, functions |
| Returns | true / false |
| Considers the prototype | Yes |
| Checks the value | No |
Comparison examples
| Check | Result | Explanation |
|---|---|---|
'name' in { name: 'Tim' } | true | the key exists |
'email' in { name: 'Tim' } | false | the key does not exist |
0 in ['a', 'b'] | true | index 0 exists |
2 in ['a', 'b'] | false | index 2 does not exist |
'toString' in {} | true | inherited from Object.prototype |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.