Is there a “not in” operator in JavaScript for checking object properties?
JavascriptObjectPropertiesOperatorsJavascript Problem Overview
Is there any sort of "not in" operator in JavaScript to check if a property does not exist in an object? I couldn’t find anything about this around Google or Stack Overflow. Here’s a small snippet of code I’m working on where I need this kind of functionality:
var tutorTimes = {};
$(checked).each(function(idx){
id = $(this).attr('class');
if(id in tutorTimes){}
else{
//Rest of my logic will go here
}
});
As you can see, I’d be putting everything into the else
statement. It seems wrong to me to set up an if
–else
statement just to use the else
portion.
Javascript Solutions
Solution 1 - Javascript
> It seems wrong to me to set up an if/else statement just to use the else portion...
Just negate your condition, and you'll get the else
logic inside the if
:
if (!(id in tutorTimes)) { ... }
Solution 2 - Javascript
Personally I find
if (id in tutorTimes === false) { ... }
easier to read than
if (!(id in tutorTimes)) { ... }
but both will work.
Solution 3 - Javascript
As already said by Jordão, just negate it:
if (!(id in tutorTimes)) { ... }
Note: The above test if tutorTimes has a property with the name specified in id, anywhere in the prototype chain. For example "valueOf" in tutorTimes
returns true because it is defined in Object.prototype.
If you want to test if a property doesn't exist in the current object, use hasOwnProperty:
if (!tutorTimes.hasOwnProperty(id)) { ... }
Or if you might have a key that is hasOwnPropery you can use this:
if (!Object.prototype.hasOwnProperty.call(tutorTimes,id)) { ... }
Solution 4 - Javascript
Two quick possibilities:
if(!('foo' in myObj)) { ... }
or
if(myObj['foo'] === undefined) { ... }
Solution 5 - Javascript
you can set the condition to be false
if ((id in tutorTimes === false)) { ... }
Solution 6 - Javascript
I know this is old, but here's another option that also looks nice.
if (!tutorTimes[id]) {...}
Similar pitfalls to someone reassigning undefined