31
loading...
This website collects cookies to deliver better user experience
keys()
method available in the global Object
object and then use the length
property in the array
returned from the method in JavaScript.// empty object
const emptyObj = {};
// get the number of keys
// present in the object
// using the Object.keys() method
// then use the length property to get the
// number of keys present
const numberOfKeysPresent = Object.keys(emptyObj).length;
// check using an if statement
// add emptyObj to check for null and undefined values
if (emptyObj && numberOfKeysPresent) {
console.log("Object is not empty since it has 1 or more key in it.");
} else {
console.log("Object is empty.");
}
// empty object
const emptyObj = {};
emptyObj
object is empty, we can use the Object.keys()
method and then use the length
property in the array
retuned from the method like this,// empty object
const emptyObj = {};
// get the number of keys
// present in the object
// using the Object.keys() method
// then use the length property to get the
// number of keys present
const numberOfKeysPresent = Object.keys(emptyObj).length;
Object.keys()
acceptsobject
as an argument to the methodarray
of keys present in the objectemptyObj
object, we can say that:0
, then it is empty0
, then the object is not empty since it has 1 or more keys present in it.if
statement like this,// empty object
const emptyObj = {};
// get the number of keys
// present in the object
// using the Object.keys() method
// then use the length property to get the
// number of keys present
const numberOfKeysPresent = Object.keys(emptyObj).length;
// check using an if statement
if (numberOfKeysPresent) {
console.log("Object is not empty since it has 1 or more key in it.");
} else {
console.log("Object is empty.");
}
null
and undefined
values, we can also check to see if the object is present like this,// empty object
const emptyObj = {};
// get the number of keys
// present in the object
// using the Object.keys() method
// then use the length property to get the
// number of keys present
const numberOfKeysPresent = Object.keys(emptyObj).length;
// check using an if statement
// add emptyObj to check for null and undefined values
if (emptyObj && numberOfKeysPresent) {
console.log("Object is not empty since it has 1 or more key in it.");
} else {
console.log("Object is empty.");
}
conditional (ternary) operator
like this,// empty object
const emptyObj = {};
// get the number of keys
// present in the object
// using the Object.keys() method
// then use the length property to get the
// number of keys present
const numberOfKeysPresent = Object.keys(emptyObj).length;
// check using conditional (ternary) operator
emptyObj && numberOfKeysPresent
? console.log("Object is not empty since it has 1 or more key in it.")
: console.log("Object is empty.");