The in
operator can tell you whether a key exists in an object or any of the objects in its prototype chain. The hasOwnProperty
function can tell you whether that key exists in the object itself (not in any of the objects on its prototype chain).
if ("foo" in obj) {
// `obj` or an ancestor has a key called "foo"
}
if (obj.hasOwnProperty("foo")) {
// `obj` has a key called "foo"
}
In your example, it wouldn't really matter which one you used because your object is just an Object
({}
=> new Object()
), so it doesn't have much of a prototype chain. But it can be relevant, for example, if you're looking at custom properties you've added to other objects, like:
var a = [1, 2, 3, 4];
a.foo = "testing";
alert("push" in a); // 1. alerts "true"
alert(a.hasOwnProperty("push")); // 2. alerts "false"
alert("foo" in a); // 3. alerts "true"
alert(a.hasOwnProperty("foo")); // 4. alerts "true"
#1 above alerts true because all arrays inherit the push
property from Array.prototype
(it refers to a function that pushes a value onto the end of the array). #2 alerts false because the push
property is from the prototype, not actually on the object itself. #3 and #4 alert true because the foo
property exists on the object itself.
Side note
What you have there isn't JSON, it's Javascript Object Literal Notation, of which JSON is a subset. You have used a literal (just like a "string literal") to create an object and have assigned it to a variable. I only mention this because object literals can have more in them (including functions) and have a wider syntax. The part within the {}
in your example is valid JSON, though, since you used double quotes on both the keys and the values, didn't include "undefined" anywhere, and didn't include any functions. :-)