How to use the "in" operator in JavaScript?


In this article, we are going to explore the 'in' operator and how to use it in JavaScript. The in operator is an inbuilt operator in JavaScript that is used for checking whether a particular property exists in an object or not. It will return true if the property exists, else false is returned.

Syntax

prop in object

Parameters

This function accepts the following parameters as described below −

  • prop − This parameter holds the string or symbol that represents a property name or the array index.

  • object − This object will be checked if it contains the prop or not.

Return value − This method will return either true or false if the specified property is found in the object or not.

Example 1

In the below example, we are going to find if the property exists or not by using the ‘inin’ operator in JavaScript.

# index.html

<html>
<head>
   <title>IN operator</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script>
      // Illustration of in operator
      const array = ['key', 'value', 'title', 'TutorialsPoint']
      
      // Output of the indexed number
      console.log(0 in array) //true
      console.log(2 in array) //true
      console.log(5 in array) //false
      
      // Output of the Value
      // you must specify the index number, not the value at that index
      console.log('key' in array) //false
      console.log('TutorialsPoint' in array) // false
      
      // output of the Array property
      console.log('length' in array)
   </script>
</body>
</html>

Output

The above program will produce the following output in the Console.

true
true
false
false
false
true

Example 2

In the below example, we illustrate the in operator.

# index.html

<html>
<head>
   <title>IN operator</title>
</head>
<body>
   <h1 style="color: red;">
      Welcome To Tutorials Point
   </h1>
   <script>
      // Illustration of in operator
      const student = { name: 'Bill', class: 'IX', subjects: 'PCM', age: '16' };
      console.log('name' in student);
      delete student.name;
      console.log('name' in student);
      if ('name' in student === false) {
         student.name = 'Steve';
      }
      console.log(student.name);
   </script>
</body>
</html>

Output

The above program will produce the following result in the Console.

true
false
Steve

Updated on: 28-Apr-2022

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements