Home >Web Front-end >JS Tutorial >Mastering or Operator in no JavaScript
Discover how to Check Object Properties
If you program in JavaScript, you may have come across situations where you needed to know whether a certain property exists in an object, and that's where the in operator comes in. I'll show you how it works, how to use it and why it can be more efficient than other ways of checking properties on an object.
The in operator is used in JavaScript to check whether a property exists on an object. The cool thing is that it not only checks the properties directly defined in the object, but also those inherited from the prototypes.
The syntax is very simple:
'propriedade' in objeto;
If the property exists, it returns true and if it does not exist, false. It seems simple, right? But its usefulness goes beyond a simple check. Would you like to see some examples?
To begin with, let's see a basic example of using the in operator to check a direct property.
const carro = { marca: 'Toyota', ano: 2020 }; console.log('marca' in carro); // true console.log('modelo' in carro); // false
Here, we have a car object with the brand and year properties. When we use 'brand' in car, the result is true, as the brand property exists directly in the object. 'model' in carro returns false, since this property has not been defined.
This type of check is great for avoiding errors when trying to access properties that don't exist. Ever tried to access a non-existent property and broken the code? I already! ?
Now, look how the in operator also detects properties inherited from the prototype
const pessoa = { nome: 'Ana' }; console.log('toString' in pessoa); // true
In this case, the person object does not have the toString property directly, but this function is inherited from Object.prototype. The in operator can see this and returns true.
Sometimes you may want to check if any inherited functionality is available in the object. This can save you in some more complex situations.
Now let's make a comparison with another way to check properties, the hasOwnProperty method. It only checks if the property was defined directly on the object, ignoring inherited ones.
const pessoa = { nome: 'Ana' }; console.log(pessoa.hasOwnProperty('toString')); // false console.log('toString' in pessoa); // true
The hasOwnProperty method returns false for toString, as this property is not directly on the person object. Meanwhile, the in operator returns true, as it also considers inherited properties.
The answer is the most talked about when asking a senior developer anything, it depends.
The above is the detailed content of Mastering or Operator in no JavaScript. For more information, please follow other related articles on the PHP Chinese website!