JavaScript `in` Operator Tutorial

In this section, we will learn what the `in` operator is and how to use it in JavaScript.

What is in Operator in JavaScript?

When we want to know if the name of a property exists in an object or its chain of prototype objects, we can use the `in` operator.

JavaScript `in` Operator Syntax:

propertyName in targetObject

JavaScript `in` Operator Operands:

The `in` operator takes two Operands:

  • The first operand is the one we put on the left side of this operator and is the name of the property we want to see if the target object has it or not.
  • The second operand, which is set on the right side of the operator, is a reference to the target object that we want to check its properties for the specified property name.

JavaScript `in` Operator Return Value:

The return value of the `in` operator is a boolean value.

  • If the target object contained the specified property name, then the return value will be true.
  • Otherwise, if the target object didn’t have the specified property name, then the return value of this method becomes false.

Note: the object and its chain of prototype objects all will be checked for the target property.

Example: using `in` operator in JavaScript

const obj = {
  firstName : "Omid",
  lastName: "Dehghan",
  age: 30
}
console.log("firstName" in obj);
console.log("lastName" in obj);
console.log("email"in obj);

Output:

true

true

false

Here the `obj` object has `firstName` and `lastName` properties and that’s why we got the true value for these two properties.

But this object does not have the `email` property and for that reason, we got the value false on the output.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies