Javascript check for not null
Below is a code snippet, where we retrieve a form value. Before further processing, check if the value is not null.
var val = document.FileList.hiddenInfo.value;
alert("val is " + val); // this prints null which is as expected
if (val != null)
{
alert("value is "+val.length); // this returns 4
}
else
{
alert(“value* is null”);
}
Any ideas why it happens so?
I’ve bumped into this a lot over my 6+ years working with JavaScript.
The thing is, when you see val.length
returning a value—even when you’re expecting null
—chances are, it’s actually an empty string (""
) rather than null
. This is a classic catch in JavaScript. Remember, empty strings aren’t the same as null
, and val != null
won’t catch them.
If you’re aiming for a cleaner check for javascript not null and not an empty string, try this:
if (val != null && val !== "") {
alert("value is " + val.length);
} else {
alert("value* is null or empty");
}
This way, you’re making sure the value is neither null
nor an empty string before attempting to access its .length
.
Yeah, totally agree with @kumari_babitaa —been debugging this kind of stuff for years.
Just to add a bit more context: in JavaScript, empty strings are considered falsy, but they still have a length of 0. So if you’re getting a length of 4, chances are your variable isn’t empty—it has 4 characters in it! This is why javascript not null checks need to go a step further and also account for non-empty strings.
Here’s a slightly more defensive approach:
if (val !== null && val !== "") {
alert("value is " + val.length);
} else {
alert("value* is null or empty");
}
This ensures that you don’t end up alerting a length from something unintended—like a leftover string.
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.