JavaScript - in operator
The JavaScript in operator returns true if the specified property is in the specified object. The syntax for using this operator is given below:
Syntax
propertyName in objectName
Parameters
propertyName |
Specify a string, numeric, or symbol expression representing a property name or array index. |
objectName |
Specify the name of an object to check if it (or its prototype chain) contains the property with specified name (propertyName). |
Example: using in operator with an Array
The example below shows the usage of in operator when used with an array.
var Numbers = [10, 20, 30, 40, 50] //returns false document.write("60 in Numbers : ", (60 in Numbers), "<br>"); //returns false document.write("'abc' in Numbers : ", ('abc' in Numbers), "<br>"); //returns false - specify the index number //not the value at that index document.write("10 in Numbers : ", (10 in Numbers), "<br>"); //returns true document.write("0 in Numbers : ", (0 in Numbers), "<br>"); //returns true (length is an Array property) document.write("length in Numbers : ", (length in Numbers), "<br>");
The output of the above code will be:
60 in Numbers : false 'abc' in Numbers : false 10 in Numbers : false 0 in Numbers : true length in Numbers : true
Example: using in operator with built-in objects
The example below shows the usage of in operator when used with built-in objects.
var MyString = new String('Hello'); //returns true document.write("'PI' in Math : ", ('PI' in Math), "<br>"); //returns true (length is a String property) document.write("length in MyString : ", (length in MyString), "<br>");
The output of the above code will be:
'PI' in Math : true length in MyString : true
Example: using in operator with custom objects
The example below shows the usage of in operator when used with custom objects.
var Person = { name: 'John', age: 25, city: 'London' } //returns true document.write("'name' in Person : ", ('name' in Person), "<br>"); //returns false document.write("'hobby' in Person : ", ('hobby' in Person), "<br>");
The output of the above code will be:
'name' in Person : true 'hobby' in Person : false
❮ JavaScript - Operators