diff --git a/collections/object/check-if-an-object-has-a-property.md b/collections/object/check-if-an-object-has-a-property.md new file mode 100644 index 00000000..9acc5c68 --- /dev/null +++ b/collections/object/check-if-an-object-has-a-property.md @@ -0,0 +1,15 @@ +~~~ javascript +const hasProp = (obj, prop) => typeof obj[prop] !== "undefined"; + +// Or +const hasProp = (obj, prop) => obj.hasOwnProperty(prop); + +// Or +const hasProp = (obj, prop) => prop in obj; + +// Example +const user = { id: 0, name: "John Doe" }; + +hasProp(user, "id") // true +hasProp(user, "email") // false +~~~