Home » Javascript » Javascript “not in” operator for checking object properties

Javascript “not in” operator for checking object properties

Posted by: admin November 29, 2017 Leave a comment

Questions:

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 SO. 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…

Answers:

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

Questions:
Answers:

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

Questions:
Answers:

Two quick possibilities:

if(!('foo' in myObj)) { ... }

or

if(myObj['foo'] === undefined) { ... }

Questions:
Answers:

Working in NodeJS .. for some reason, I have to do a check for null as well as NOT IN

if ( ! ('job_id' in req.params) || req.params.job_id == null)
{
 // ..
}

Questions:
Answers:

Jordão’s answer is the way to go if you are used to the “not in” syntax.

An alternative, that hasn’t been mentioned, is the use of indexOf method.

indexOf() returns -1 when object is not in array

if (tutorTimes.indexOf(id) < 0) {
    // your code
}

Questions:
Answers:

Few of the options are

  1. Object.hasOwnProperty(‘propertyname’)

  2. for in loop

  3. forEach loop

  4. Loop the array and then reach the required property with Object.propertyName

Read about all of them ,they are very important concept in JS and very helpfull

Enjoy Js