How do you reliably check for an empty, undefined, or null string in JavaScript? | A1Lab@FahadM to JavaScriptEnglish •
edit-2
12 days ago

How do you reliably check for an empty, undefined, or null string in JavaScript?

message-square
0

Use optional chaining with .trim() (!str?.trim()), which safely catches null, undefined, empty strings "", and whitespace-only strings " " in a single expression.

Reliable Empty String Check (Recommended)

function isBlank(str) {
  return !str || str.trim().length === 0;
}

console.log(isBlank(null));       // true
console.log(isBlank(undefined));  // true
console.log(isBlank(""));         // true
console.log(isBlank("   "));      // true
console.log(isBlank("A1Lab"));    // false

Note on Non-String Inputs

If the variable might hold a number or object, verify typeof str !== "string" first before calling .trim().