Skip to main content

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

javascript
propName in object

Where:

  • propName is a string (or an expression coerced to a string),
  • object is an object, array, or another structure with keys.

Example with an object

javascript
const user = { name: 'Tim', age: 25 }; console.log('name' in user); // true console.log('age' in user); // true console.log('email' in user); // false

The in operator returns true if the property exists in the object (even if its value is undefined).


Features

Even if the property's value is undefined, in will still return true:

javascript
const obj = { a: undefined }; console.log('a' in obj); // true console.log(obj.a === undefined); // true

In other words, in checks for the presence of a key, not its value.


Example with an array

javascript
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 index

JS treats array indexes as properties: arr[0] is equivalent to arr['0'].


Example with inheritance (via the prototype)

The in operator checks not only own properties, but also ones inherited through the prototype.

javascript
const person = { name: 'Tim' }; console.log('toString' in person); // true, because it's inherited from Object.prototype

To check only own properties, use obj.hasOwnProperty('key'):

javascript
person.hasOwnProperty('toString'); // false person.hasOwnProperty('name'); // true

Example with a class

javascript
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:

javascript
'length' in null; // TypeError 'length' in undefined; // TypeError

So before checking, make sure the variable is not null or undefined.


Summary

ChecksThe presence of a key (property / index)
Works withObjects, arrays, functions
Returnstrue / false
Considers the prototypeYes
Checks the valueNo

Comparison examples

CheckResultExplanation
'name' in { name: 'Tim' }truethe key exists
'email' in { name: 'Tim' }falsethe key does not exist
0 in ['a', 'b']trueindex 0 exists
2 in ['a', 'b']falseindex 2 does not exist
'toString' in {}trueinherited from Object.prototype

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.