1

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.

Tamás Pap
  • 16,112
  • 13
  • 65
  • 94
  • `typeof` is an operator not a function, you should get rid of the `()` around the values you are testing with it. – Quentin Feb 14 '12 at 09:51
  • @Quentin: it's arguable, some prefer to use parenthesis for all control statements to make the code more consistent and readable. For instance, some prefer to write `return (true)` instead of `return true`. It's a matter of preferences (and irrelevant to the question). – haylem Feb 14 '12 at 09:58
  • possible duplicate of [Javascript isset() equivalent](http://stackoverflow.com/questions/2281633/javascript-isset-equivalent) – Gajus Nov 18 '14 at 07:55

4 Answers4

4

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']));
Andrey Selitsky
  • 2,579
  • 3
  • 26
  • 41
  • 1
    You are right. I just was wondering if it is possible to create a php like isset function. In php you can do this: var_dump(isset($a['not']['exists'])); Thanks for response! – Tamás Pap Feb 14 '12 at 09:51
3

that won't work, and you can't make it work. what happens is this: the js engine tries to evaluate a['not'] and get's "undefined", then it tries to evaluate the property 'existent' of the undefined and you get that error. all of that happens before the call to your function...

what you can do is something like:

var isset = function(obj, props) {
    if ((typeof (obj) === 'undefined') || (obj === null))
        return false;
    else if (props && props.length > 0)
        return isset(obj[props.shift()], props);
    else
        return true;
};

then you call it like this:

var a = [];

// Test 1
alert(isset(a, ['not']);
// Test 2
alert(isset(a, ['not', 'existent']));

(**this just a pseudo code, you might need to modify it a bit to actually work)

Nitzan Tomer
  • 120,901
  • 33
  • 273
  • 264
1

Test 2 will not work because "a['not']['existent']" value resolution precedes "isset" function call, and results in a runtime error.

Sergey Ilinsky
  • 29,849
  • 9
  • 51
  • 56
0

Well, You can do right this:

1) as we do in php:

$vara = "abc";
$a =0;

 while(isset($vara[a]){
a++;
} 

2) as I do in javascript:

vara = "abc";
 while (vara[a] != null){
a++;
}
arghtype
  • 3,966
  • 11
  • 39
  • 54
aasim
  • 1