I had the same question as posed here: Checking if a key exists in a JavaScript object? .
However, I’m looking for a method which will work in all major browsers including IE 6+. The method I saw which I liked is the use of the in operator, which I’ve never seen before.
I tried something different in google chrome which seemed to work, but I’d like to know why its not used instead of the in operator.
For reference:
var data = {foo : "bar"};
console.log("foo" in data); // true
console.log("bar" in data); // false
My proposal:
var data = {foo : "bar"};
console.log(!!data.foo); // true
console.log(!!data.bar); // false
Are there any drawbacks with my (second) method?
You seem to be looking for an alternative because you didn’t know about the
inoperator before, and assumed it was not supported by all major browsers. In fact, it is supported by all major browsers, including IE6. From MSDN:I’ll refrain from explaining the drawbacks of your proposed approach, since another answer and the comments already do that.