The first one is the typical way to go actually. Works fine specially if you have typings, like with TypeScript.
The second one is just the same but with a bit of overhead (each time you enter/exit a function, adss a bit of overhead), although is really small overhead only noticeable when you have tons of iterations. You can detect the arguments dynamically:
const nullobj = {
value1: "yay",
value2: "",
value3: 23,
value4: null
};
const obj = {
value1: "yay",
value2: "",
value3: 23,
value4: "ok"
};
function checkArgumentsNull(...args) {
for (let v of args) {
if (v == null) {
return true;
}
}
return false;
}
console.log("nullobj:", checkArgumentsNull(nullobj.value1, nullobj.value2, nullobj.value3, nullobj.value4));
console.log("obj:", checkArgumentsNull(obj.value1, obj.value2, obj.value3, obj.value4));
But if you are going to check dynamically for arguments, you can check dynamically for properties, which is easier. Just saw your edit and this one can be easily converted to a recursive one that will check for sub-objects. Actually all functions here can be converted to recursive ones following this principle:
const nullobj = {
value1: {
ok: "ok",
notok: null
},
value2: "",
value3: 23,
value4: "ok"
};
const obj = {
value1: {
ok: "ok",
notok: "no"
},
value2: "",
value3: 23,
value4: "ok"
};
function checkPropertiesNull(obj) {
for (let v in obj) {
if (obj[v] == null || (typeof obj[v] === "object" && checkPropertiesNull(obj[v]))) {
return true;
}
}
return false;
}
console.log("nullobj:", checkPropertiesNull(nullobj));
console.log("obj:", checkPropertiesNull(obj));
And for the sake of modern JavaScript, you can even pass an iterator, and you can check whatever iterable object you can imagine of (object, arrays, maps, sets, etc):
const nullobj = {
value1: "yay",
value2: "",
value3: 23,
value4: null
};
const obj = {
value1: "yay",
value2: "",
value3: 23,
value4: "ok"
};
const nullarr = ["ok", "yay", null];
const arr = ["ok", "yay", "yay2"];
function checkIteratorNull(it) {
for (let v of it) {
if (v == null) {
return true;
}
}
return false;
}
console.log("nullobj:", checkIteratorNull(Object.values(nullobj)));
console.log("obj:", checkIteratorNull(Object.values(obj)));
console.log("nullarr:", checkIteratorNull(nullarr));
console.log("arr:", checkIteratorNull(arr));