In JavaScript, we can check if an array has at least one element by checking its length
property. But object literals don't have a length
property, so how can we check if they have at least one property?
The answer? The Object.keys()
method.
As the MDN Web Docs explain, the
.Object.keys()
method returns an array of a given object's own enumerable property names
This means we can get an object's keys as an array, then make sure the array's length
property is greater than zero.
const videoGame = {
title: "Skyrim",
series: "The Elder Scrolls",
developer: "Bethesda"
};
if (Object.keys(videoGame).length > 0) {
// This will run since the videoGame object has three properties
}
Note: You could just check if (Object.keys(videoGame).length) {}
. You don't need to check if it's greater than zero, because if it is indeed zero, then it will be falsy. Anything above zero is truthy. However, I think the explicit check makes the code more obvious.
The Object.keys()
method is supported in all modern browsers and in IE9+, so you can use it everywhere.