I usually used if(value) to check value is null or not. But now I know false or 0 can be false. So I used if(value == null) but in this time, that null doesn't contain '' like.
I want to check that 0, false(have specific value) as true, and I want to check that '', undefined, null as false
What will be good way to check these values simply? Is there something to notice bout like this more?
Maybe this small helper function helps? Play with it in Stackblitz.
test();
test(42);
test(Infinity);
test(null);
test(0);
test({});
test(new Map());
function test(someValue) {
if (hasValue(someValue)) {
return console.log(`${someValue} is truthy`);
}
return console.log(`${someValue} is falsy`);
}
function hasValue(v) {
// Objects are always considered values
if (v instanceof Object) {
return true;
}
const falsies2Check = [false, 0, '', null, undefined, Infinity];
return falsies2Check.find(f => f === v || isNaN(v)) === undefined ? true : false;
}
Just check for the possible values normally.
const isFalsy = param => (param === null) || (param === "") || (typeof param === "undefined")
isFalsy(null); // true
isFalsy(0); // false
I want to check that
0,false(have specific value) as true.
if(!isFalsy(value))