There are a variety of places where I need to check if a JavaScript variable is null or empty string so I wrote an extension method that looks like this:
Object.prototype.IsNullOrEmptyString = function()
{
return (this == null || (typeof this === "string" && this.length == 0));
}
I then call it like so:
var someVariable = null;
if (someVariable.IsNullOrEmptyString())
alert("do something");
But that doesn’t work because, at the point of evaluation in the if statement, someVariable is null. The error I keep getting is “someVariable is null”.
You can see it live here: http://jsfiddle.net/AhnkF/ (run in Firefox and notice the error console)
Is there anyway to do what I want and have a single extension method check for null and other things at the same time?
nulldoes not have any properties or methods. You have to create a function, and pass the variable, so it can be tested. Note: To test whether a variable is really an empty string, using=== ""is recommended.** about
==and===. The following comparisons aretrue: