How to Check for Empty VAR in Javascript

How to Check for Empty VAR in Javascript thumbnail
Empty jars are just disappointing. Empty vars in your JavaScript could cause errors.

The variables in your JavaScript code may be "empty," not initialized (never assigned a value) or not declared. Empty values are based on type of the variable. Empty values include: '' (string), null (object), false (boolean) and 0 (numerical values). When a variable is not initialized, it does not have a type and its value is "undefined." Checks for empty and undefined values are done by testing the variable with the "not" operator. The "not" operator returns an error for undeclared variables, so the variable needs to be checked by testing if the variable's type has been defined.

Things You'll Need

  • Text or JavaScript code editor
Show More

Instructions

    • 1

      Open your JavaScript in your favorite text or code editor. Locate the section where you need to check if your variable has been declared and assigned a non-empty value.

    • 2

      Start an if-block, replacing "myVar" in the following code with your variable's name:

      if (typeof myVar === 'undefined' || !myVar) {

      The first check, "typeof myVar === 'undefined'," tests if your variable has been declared. If it has not been declared, the "typeof" operator returns "undefined" and the first check passes. If your variable has been declared and initialized, the second condition is checked. The second check, "!myVar," uses the "not" operator (!) to test if your variable holds an empty value. The "not" operator will return true if the value is '', false, 0, or "undefined."

    • 3

      Write the code you want to execute when your variable is undeclared or empty. For example, you may want to pop up an alert, write a message in the document text or bail out by returning from the function. End the if-block with a closing curly bracket "}".

    • 4

      Create an else-block containing the code you want to execute if your variable contains a non-empty value. If you bailed out of the if-block with a "return," the else-block is not required.

Tips & Warnings

  • If you want different code to execute, depending on whether the variable is undeclared or simply contains an empty value, break the if-block into an if-elseif-block. For example, you may want to pop up an alert and bail out if the variable is undeclared, but change an empty value so the script can continue:

  • if (typeof myVar === 'undefined') {

  • alert ("Error! myVar is undeclared!") ;

  • return ;

  • }

  • else if (!myVar) {

  • myVar = "John Doe" ;

Related Searches:

References

Resources

  • Photo Credit empty glass jar image by vadim kozlovsky from Fotolia.com

Comments

You May Also Like

Related Ads

Featured