javascriptin-operatoroptional-chaining

Can Optional Chaining be alternative of 'in' operator in Javascript


I often saw in operator in some library of Javascript. but I think in operator has risk of causing human errors. because we have to write property name as string type.

I think optional chaining could be alternative of in operator and It looks more safe. we can get help of intelligence of IDE during writing code.

what is the benefit of using in keywords instead of Optional Chaining?

enter image description here


Solution

  • AFAIK, in is used to get to know whether the property exists in an object or its prototype or not.

    const address = {
      zipCode: 1234,
      country: 'usa',
      city: 'new York',
    };
    
    if ('zipCode' in address) {
      console.log('This is address from in checking');
    }

    and if you are using optional chaining then you are checking the value to be truthy or not

    const address = {
        zipCode: 1234,
        country: 'usa',
        city: 'new York',
    };
    
    if (address?.zipCode) {
        console.log('This is address from optional chaining');
    }


    But think of a situation where the value of that property is a falsy value then the in operator will give you the result of property existence. If the value is a falsy value then you have to make additional checks to know whether the property exists or not.

    Value can be anything so you have to make necessary checks in optional chaining

    const address = {
      zipCode: 0,
      country: 'usa',
      city: 'new York',
    };
    
    if ('zipCode' in address) {
      console.log('This is address from in checking');
    }
    
    if (address?.zipCode) {  // Won't work
      console.log('This is address from optional chaining');
    }
    
    if (address?.zipCode || address?.zipCode === 0) {  // Will work with extra checks
      console.log('This is address from optional chaining');
    }