Is there a “not in” operator in JavaScript for checking object properties?

Aaron picture Aaron · Nov 1, 2011 · Viewed 209.3k times · Source

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 ifelse statement just to use the else portion.

Answer

Jordão picture Jordão · Nov 1, 2011

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)) { ... }