How do you reliably check for an empty, undefined, or null string in JavaScript?
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().
You must log in or register to comment.
