Javascript tutorials - In operator examples

In operator is inbuilt operator provided in javascript language, This covers the usage of In operator in the following cases

Javascript In operator

in operator in javascript used to find the property presents in an object.


name in objects

Syntax contains two operands

Left hand operand is an property string name or array index. Right hand operand is an object to check

This operator returns true for following cases

  • if left hand operator or name is an property of an object.
  • if array index exists in an array of an object

Return false for below cases

  • Not valid property of an objects
  • Not an valid array index of an given right hand array object

Check valid index exists in an array using in operators

In operator checks valid index exists in an given array Please note that, this operator checks only index not its values

In the give below example, Created an array of three elements, so valid index are 0,1,2

in operator returns true for index=0,1,2,false- index>=3

let array = [43,1, 21]
console.log(0 in array)// true
console.log(1 in array)// true
console.log(2 in array)// true
console.log(3 in array)// false

This will be very useful to check invalid index validation against arrays to avoid undefined values.

Check property of an object in Javascript

in operator checs an property exists in an object, It does not check property value.

Let see an simple object property check example

const emp = {id: '1', name: 'Franc'};
console.log('id' in emp); //true
console.log('name' in emp); //true
console.log('Franc' in emp); //false

Here is one more example of class extend checking property check example

Declared Animal with name property Declared Lion with legs property by extending Animal Created object for Lion,name and legs on lion object returns true property value animal returns false.

class Animal {
  constructor() { = "animal"
class Lion extends Animal {
  constructor() {
    this.legs = "2"
const lion = new Lion()
console.log('name' in lion) //true
console.log('legs' in lion) //true
console.log('animal' in lion) //false

In operator enum Usage

let’s declare an Enum

export enum HttpResponseStatus {
    SUCCESS = 200,

In operator used in enum data type for following use cases

Check string exists in Enum typescript or Javascript

In the below example, This operator used to chehck string and value presented in Enum data. false is return if there is no property or its value exists in Enum typescript

console.log(200 in HttpResponseStatus); // true
console.log('SUCCESS' in HttpResponseStatus); // true
console.log('600' in HttpResponseStatus);// false

Iterate Enum data

These also be used to iterate the enum properties when used in for loop. The following examle prints only string propertie, not its values

for (let element in HttpResponseStatus) {
    if (isNaN(Number(element))) {

And the output is

Similar Posts