hasOwnProperty with more than one property

There are two things going on here.

First, hasOwnProperty only takes one argument. So it'll ignore whatever other arguments you pass to it.

Second, (and I'm simplifying slightly here) it's going to convert that first argument to a String, and then check to see if the object has that property.

So let's look at your test cases:

The reason { "a": 1, "b": 2 }.hasOwnProperty( "a", "b"); returns true is because it's ignoring the second argument. So really it's just checking for "a".

{ "a": 1, "b": 2 }.hasOwnProperty( ["a", "b"]) returns false because the first argument, ["a", "b"], gets converted to "a,b", and there's no { "a": 1, "b": 2 }["a,b"].

To find out if a given object has all the properties in an array, you can loop over the array and check each property, like so:

function hasAllProperties(obj, props) {
    for (var i = 0; i < props.length; i++) {
        if (!obj.hasOwnProperty(props[i]))
            return false;
    }
    return true;
}

Or, if you're feeling fancy, you can use the every function to do this implicitly:

var props = ["a", "b"];
var obj = { "a": 1, "b": 2 };
var hasAll = props.every(prop => obj.hasOwnProperty(prop));

I hope that helps clarify things. Good luck!


If you want to check the object's own properties, you could use the Object.getOwnPropertyNames method. It returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly upon a given object.

let o = { "a": 1, "b": 2 };
Object.getOwnPropertyNames(o).forEach(k => console.log(`key: ${k}, value: ${o[k]}`));


Given the documentation, it seems that the hasOwnProperty() method takes either a string or a symbol as an argument. So I think hasOwnProperty() isn't capable of taking a collection of strings and testing if the object has each one as a property.

I think another approach would be to take the array of strings and iterate through each one. Then for each string in your array (the properties you want to test for), you could test if the object has that property. Here's an example:

const o = new Object();
var propsToTest = ['a', 'b'];
o.a = 42;
o.b = 40;

var hasProperties = true;
propsToTest.forEach(function(element) {	// For each "property" in propsToTest, verify that o hasOwnProperty
  if(!o.hasOwnProperty(element))
    hasProperties = false;
});

console.log(hasProperties);