Search code examples
javascriptisset

Javascript isset function


I created an isset function to check if a variable is defined and not null. Here's my code:

isset = function(a) {
    if ((typeof (a) === 'undefined') || (a === null))
        return false;
    else
        return true;
};
var a = [];

// Test 1
alert(isset(a['not']); // Alerts FALSE -> works OK
// Test 2
alert(isset(a['not']['existent'])); // Error: Cannot read property 'existent' of undefined

Any suggestion to make my function work for test 2? Thanks.


Solution

  • You are trying to check property of an undefined object. It doesn't make any sense. You could write like this:

    alert(isset(a['not']) && isset(a['not']['existent']));