Understand javascript nulls

satya - Saturday, February 25, 2012 9:38:42 AM

javascript null

javascript null

Search for: javascript null

satya - Saturday, February 25, 2012 9:41:19 AM

Good article on understanding javascript nulls

Good article on understanding javascript nulls

satya - Saturday, February 25, 2012 9:49:11 AM

In java script 'null' is an object

In java script "null" is an object

satya - Saturday, February 25, 2012 9:53:33 AM

In javascript you have '==' and '==='

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

satya - Saturday, February 25, 2012 9:56:15 AM

type coercions


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

satya - Saturday, February 25, 2012 9:57:23 AM

You can do this


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

satya - Saturday, February 25, 2012 10:00:03 AM

what does this mean


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".

satya - Saturday, February 25, 2012 10:00:22 AM

what does this mean


if (x === null)
{
}

satya - Saturday, February 25, 2012 10:02:37 AM

it will return false because

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

satya - Saturday, February 25, 2012 10:06:22 AM

what about this


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.

satya - Saturday, February 25, 2012 10:25:42 AM

First attempt


//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;
}