Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Checking for undefined in Javascript

    • 0
    • 4
    • 1
    • 1
    • 0
    • 0
    • 0
    • 0
    • 141
    Comment on it

    Undefined is a variable in global scope. A variable that has not been assigned any value is referred as undefined.

    You can check for undefined in various ways.Here are some ways to check :-

    1. Checking via Strict equality(===)

    var a;
        if(a=== undefined)
    {
       // these statements execute
    }
    

    In the above code, the variable a is not defined, and the if statement evaluates to true.

    1. Checking via typeof operator

    var a;
        if(typeof a === 'undefined')
    {
       // these statements execute
    }

    Typeof operator also works for undeclared variables,i.e,it does not throw error even if the variable is not declared.

    // a has not been declared before
    if (typeof a === 'undefined') { // evaluates to true without errors
       // these statements execute
    }
    
    if(a === undefined){ // throws a ReferenceError
    
    }
    1. Checking via Void operator

    var a;
    if (a === void 0) {
       // these statements execute
    }

    In Javascript void works as an operator,it takes an operand,it has nothing to do with the results and returns undefined.
    We should avoid using void because it always evaluates to undefined.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: