I’ve run into this during testing edge cases—especially with form inputs.
Adding on to what @kumari_babitaa and @joe-elmoufak said, the key here is understanding that ""
(empty string) is still a valid value and has a .length
—even if it’s zero. And because JavaScript is loose with types, it’s easy to confuse that with null
.
To make your condition truly robust when checking javascript not null and ensuring it’s not an empty value either, this snippet works well:
if (val != null && val !== "") {
alert("value is " + val.length);
} else {
alert("value* is null or empty");
}
One small tip: if this logic shows up often in your codebase, you might consider wrapping it in a utility function to keep things DRY.