offline version v3


13 of 264 menu

in operator

The in operator checks if an object or an array has a property and returns true or false.

Syntax

'property' in object;

Example

Let's see how the in operator works:

let obj = { name: 'Nick', age: 23, }; console.log('name' in obj); // true console.log('age' in obj); // true console.log('test' in obj); // false

Example

Let's see how we can use the in operator to check a property in an array:

let arr = ['green', 'red', 'blue', 'pink'] console.log(0 in arr); // true, there is an element with this index console.log(4 in arr); // false, there is no element with this index console.log('four' in arr); // false, the index is required, not the element value console.log('length' in arr); // true, an array has this property

Example

Often, instead of in, they check that a property in the logical context is true:

let obj = { name: 'John', height: '177', }; if ('name' in obj) {} // checking the condition with in if (obj.name) {} // but more often it's written like this

Both options can be used. But it's always worth to remember that an empty string, 0, null, NaN and undefined in a boolean context are false. Therefore, if a property can have a similar value - it is worth to use in.

enru