The in operator helps us to check if a property is in the object. It returns true
if a property exists in the object. Otherwise false
if the property does not exist.
Here is how you use the in operator in JavaScript.
prop in object
prop
is the property name you want to check if it is present in the object.object
is the object in which the property can be.Let's see some examples that show you how to use the in operator in JavaScript.
let pdt = { name: "Coral Straight Fit Kurta", price: 1039, size: ["S", "M", "L"], color: "Coral" } console.log('price' in pdt); //true console.log('size' in pdt); //true console.log('fabric' in pdt); //false
As you can see, the price
property is in the pdt
object, so the in
operator returns true
. On the other hand, the fabric
property is not present that is why the in operator returns false
.
Using the in operator, you can also check if an inherited property exists in an object or not.
let pdt = { name: "Coral Straight Fit Kurta", price: 1039, size: ["S", "M", "L"], color: "Coral" } console.log('toString' in pdt); //true
The toString
is a method that is inherited from the Object
to the pdt
object.
The in operator is also used to check if an index is present in the array.
let arr = [11, 22, 33, 44]; console.log(1 in arr); //true console.log(3 in arr); //true console.log(4 in arr); //false
As you can see that the array has index positions from 0 to 3.
4 is not an index position, that is why the in operator returns false
.