What is the best way to check if a property in JavaScript is not an object?

I need a way to check if a property does not exist in an object, but I couldn’t find a “not in” operator in JavaScript.

Here’s a small snippet of code I’m working on:

var tutorTimes = {};

$(checked).each(function(idx){
  id = $(this).attr('class');

  if(id in tutorTimes){ }
  else{
    //Rest of my logic will go here
  }
});

It seems a bit off to set up an if-else just to use the else portion. Is there a more elegant way to achieve this in JavaScript?

Hi,

You can use !(key in object). The in operator returns true if the property exists (even if the value is undefined), so adding ! checks the opposite. This is the simplest and most direct way to express not in.

if (!(id in tutorTimes)) {
  // Property does NOT exist
}

Try using the hasOwnProperty() negation.

This checks only the object’s own properties, not anything inherited via the prototype chain. It’s safer in some cases, especially if you’re avoiding inherited keys.

if (!tutorTimes.hasOwnProperty(id)) {
  // Property does NOT exist
}

To check whether a variable is undefined, it’s recommended to use the typeof operator.

if (typeof tutorTimes[id] === 'undefined') {
  // Property does NOT exist
}

This checks if the value is literally undefined, which often means it hasn’t been set. Use this if you’re sure undefined values don’t count as “existing.”