The in
operator can indicate whether a key exists in an object or any of its prototype chain objects. The function hasOwnProperty
can determine if the key exists only in the object itself and not in its prototype chain.
if ("foo" in obj) {
// `obj` or an ancestor has a key named "foo"
}
if (obj.hasOwnProperty("foo")) {
// `obj` has a key named "foo"
}
In this scenario, it wouldn't make much difference which one is used as your object is just an instance of an Object
({}
=> new Object()
) without a significant prototype chain. However, it may be important when examining custom properties 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 shows true because all arrays inherit the push
property from Array.prototype
. #2 alerts false since the push
property belongs to the prototype, not the object itself. #3 and #4 alert true because the foo
property actually exists on the object.
Note:
The content is not JSON but JavaScript Object Literal Notation, with JSON being a subset of it. This notation allows for more elements (including functions) and greater syntax possibilities within the {}
. In your example, what's inside the {}
is valid JSON due to the usage of double quotes for keys and values, absence of "undefined," and exclusion of functions.