user10108817
user10108817

Reputation: 285

Checking existence of hash key without hasOwnProperty in JavaScript

Given this example data:

let foo = [1,2,2,3,5,3]
let seen = {}

What is the difference between the following ways to check the existence of a key? Can I run into some hiccups using the first way?

foo.filter(function(item) {
    return seen[item] ? false : (seen[item] = true);
});

vs.

foo.filter(function(item) {
    return seen.hasOwnProperty(item) ? false : (seen[item] = true);
});

Upvotes: 0

Views: 101

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

First off, as shown in the question, both are incorrect because you're not using the return value of filter (a new, filtered array). Use forEach or (on modern systems) for-of in that case. But perhaps you actually are using it and just didn't show that in your question.

Addressing your main question:

The first way will incorrectly assume something wasn't seen if it's falsy. The falsy values are 0, "", NaN, null, undefined, and of course false. (All other values are truthy.) Your second way will handle those correctly.

Another difference between your two checks is that the first gets the property regardless of where it is in the prototype chain; the second only looks at the object itself (which is probably what you want). For your example object, this really only matters for properties provided by Object.prototype such as valueOf, but...

You might also look into Set or Map.

Upvotes: 3

gautsch
gautsch

Reputation: 824

In addition to what TJ said.

hasOwnProperty will not search the prototype of the object while the bracket or dot notation will. See this example

Object.prototype.foo = 1;
var baz = {"bar": 1}

if (baz.hasOwnProperty('foo')) {
    console.log('has foo');
    return true
}

if (baz.bar) {
    console.log('has bar'); // has bar
    return true;
}

Upvotes: 0

CoderPi
CoderPi

Reputation: 13211

Short answer: there are no problems in this case for not using Object.hasOwnProperty() [wiki]

When would it be a problem?

let seen = {}

console.log(seen["constructor"]) // function Object() { [native code] }

as you can see this will also hold other strings for inherited properties like constructor of an Object. Since you are only dealing with numbers there a no such properties on Object.

Upvotes: 0

Related Questions