I am using this code to check a variable in javascript useable:
var userName;
if (userName === null
|| userName === ''
|| userName === undefined
|| userName === {}) {
console.log("useable");
}else{
console.log("unuseable");
}
is there any simple and clear way to do this action? If I use if(userName){}, this would not work:
var userName='';
if (userName) {
console.log("null");
}else{
console.log("not null");
}
if I use Object.keys(obj).length === 0, this would not work:
var obj=new Date();
if (Object.keys(obj).length === 0) {
console.log("null");
}else{
console.log("not null");
}
>Solution :
You can try a functional approach, including all of your conditions and checks in the function:
function isNull (value) {
// any falsy value: https://developer.mozilla.org/en-US/docs/Glossary/Falsy
if (!value) return true;
if (typeof value === 'object') {
// empty array
if (Array.isArray(value) && value.length === 0) return true;
// empty object
if (value.toString() === '[object Object]' && JSON.stringify(value) === '{}') return true;
}
return false;
}
let username;
if (isNull(username)) {
console.log('usable');
}
else {
console.log('not usable');
}