Quickly check whether a property exists against an object.
There is more than one way to check whether a given object has a prop - the choice if often convenience rather than performance of the said method.
Let’s see the various methods by taking this example of a simple object.
1
|
let apple = { color: "red", size: "small" };
|
Method 1: Check the value of the prop
Check whether a property exists in an object by “getting” that prop.
1
2
3
4
5
6
7
8
9
10
11
12
13
|
let apple = { color: "red", size: "small" };
// get prop and booleanify it!
console.log(!!apple["color"]); // true
// or you could simply make use of Javascript's truthy checks for non-empty strings.
// how to use the truthy check in a statement
if (apple["color"]) console.log("apple has color"); // yes, apple has color
/* output
true
apple has color
*/
|
This is easy to code and to read, but what happens if you use a property that has no value?
1
2
|
console.log("weight: ", apple["weight"]); // undefined
if (apple["weight"]) console.log("apple has weight"); // no show
|
The results are expected for an undefined prop, but let’s see the behaviour if the property exists but is falsy.
1
2
3
4
|
let apple = { color: "red", size: "small", weight: "" };
console.log('apple["weight"]', apple["weight"]); // <blank>
if (apple["weight"]) console.log("apple has weight"); // no show
|
The unexpected results are a major turn-off.
Method 2: Check for prop but give it super powers
Avoid the confusing situation with prop checks using -
- check for prop being
undefined
- optionally include
typeof
1
2
3
4
5
6
7
8
9
|
let apple = { color: "red", size: "small" };
console.log("1 weight: ", apple["weight"]); // undefined
if (apple["weight"]) console.log("1 apple has weight");
// not displayed
apple = { color: "red", size: "small", weight: "" };
console.log("2 weight: ", apple["weight"]); // <blank>
if (apple["weight"] != undefined) console.log("2 apple has weight");
// 2 apple has weight
|
You could make it even more clear by using typeof
.
1
|
if (typeof apple["weight"] != undefined) console.log("2 apple has weight"); // apple has weight
|
Method 3: Use hasOwnProperty
There is an alternate method that may be preferable in most cases - use hasOwnProperty
method against the object.
1
2
3
4
|
let apple = { color: "red", size: "small" };
console.log("apple has color:", apple.hasOwnProperty("color")); // true
console.log("apple has weight:", apple.hasOwnProperty("weight")); // false
|
Note that you could have made this more succinct/easy to remember using in
, but that may have inconsistent results -
1
|
console.log("apple has constructor?", "constructor" in apple); // true
|
The above code evaluates to true
because Javascript internally tracks props like constructor
(“non-enumerable props”) for all objects.
Summary
We saw three ways of checking for props in an object.
Further reading:
- Object vs. prototype props in Javascript
- Ways to check if an object is empty