Understand javascript nulls

javascript null

Search for: javascript null

Good article on understanding javascript nulls

In java script "null" is an object

the first one does type coercion. the second one evaluates first to see if the objects are of the same type.


value 0 becomes false
an empty string "" evaluates to false
object null evaluates to false
undefined object evaluates to false

if (typeof(x) == "undefined")
{
}

if (x == null)
{
}

First off Notice the type coercion. if "x" is undefined then it is evaluated to "false". "null" is an object and is evaluated to false. So the whole expression will evaluate to "true".


if (x === null)
{
}

"x" is undefined and "null" is typed. So the expression will evaluate to false.


if (x == "")
{
}

if "x" is undefined then it is true.

if "x" is null then it is true.

if "x" is an empty string then it is true as well.

So use this if you want a "true" if it the string is undefined, null, or empty.


//String functions
function isInValidString(s)
{
   return !isValidNonEmptyString(s);
}
function isValidString(s)
{
   return isValidNonEmptyString(s);
}
function isValidNonEmptyString(s)
{
   if (s == "")
   {
      //s is either undefined or null or if string empty
      return false;
   }
   //Assume s is a string
   var ns = s.trim();
   if (ns == "")
   {
      return false;
   }
   return true;
}