Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to make the javascript null check more clear

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading