Easy Tutorial
❮ Android Tutorial Relativelayout Android Tutorial Activity Start ❯

JavaScript Methods for Checking Null, NULL, and Undefined Values

Category Programming Techniques

In JavaScript, to check if a variable is defined, you can use the typeof operator:

Example

if (typeof someVar == 'undefined') {
  document.write("The variable someVar is undefined");
} else {
  document.write("The variable someVar is defined");
}

In JavaScript, if you only want to check whether a defined variable is true, you can use the following method directly:

Example

if (strValue) {
    // Code to execute if strValue is true
} else {
    // Code to execute if strValue is false
}

The following is a more comprehensive method using regular expressions to check if a variable is defined and not empty:

Example

if ( // Return the value of the check
        (typeof x == 'undefined')
              ||
        (x == null)
              ||
        (x == false)        //Similar: !x
              ||
        (x.length == 0)
              ||
        (x == 0)            //Here it is to check 0, no need to deliberately remove
              ||
        (x == "")
              ||
        (x.replace(/\s/g,"") == "")
              ||
        (!/[^\s]/.test(x))
              ||
        (/^\s*$/.test(x))
    ) {
  document.write("The variable is undefined or empty");
}

You can also encapsulate a method to check, including null, 0, false, etc., applicable to defined variables:

Example

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case undefined:
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
})) // false

** Click to Share Notes

Cancel

-

-

-

❮ Android Tutorial Relativelayout Android Tutorial Activity Start ❯