Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
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:

var obj=new Date();
if (Object.keys(obj).length === 0) {
    console.log("null");
}else{
    console.log("not null");
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!