Skip to content

JavaScript in operator | Example code

  • by

Use JavaScript in operator to check if the specified (given) property is in the specified object or its prototype chain. The in operator returns true if the specified property exists.

property_name in object

Here, property_name is the name of the property you want to check, and object is the object you want to search in

JavaScript in operator

A simple example code verifies if a property exists on an object.

<!DOCTYPE html>
<html>
<body>

  <script>
   const car = { make: 'BMW', model: 'X1', year: 2020 };

   console.log('make' in car);


   delete car.make;
   if ('make' in car === false) {
    car.make = 'Suzuki';
  }

  console.log(car.make);
</script>

</body>
</html> 

Output:

JavaScript in operator

The following examples show some uses of the in operator.

// Arrays
let trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']
0 in trees        // returns true
3 in trees        // returns true
6 in trees        // returns false

// Custom objects
let mycar = {make: 'Honda', model: 'Accord', year: 1998}
'make' in mycar  // returns true
'model' in mycar // returns true

Note: the in operator also checks if the property exists in the object’s prototype chain. If the property is found in the object or any of its prototypes, the in operator will return true.

Do comment if you have any doubts or suggestions on this JS operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading