0

Possible Duplicate:
php isset() equivalent in javascript

PHP example: http://codepad.viper-7.com/vo4wGI

<?php
var_dump( isset($something['deep']->property) ); // false
# because well, there is no such thing defined at all

JS kind of equivalent: http://jsfiddle.net/psycketom/Lp83m/ but doesn't work, because browsers appear to lookup the value first before trying to resolve it's type, and, if it's not found, you get

console.log( typeof something['deep'].property ); // Uncaught ReferenceError: something is not defined 

Is there a native function in JavaScript to properly resolve deep undefined properties?

Community
  • 1
  • 1
tomsseisums
  • 13,168
  • 19
  • 83
  • 145
  • I have read that question, it doesn't cover deep properties. For javascript to handle undefined case, with `typeof` it only works on existing objects inexistent properties, but I have to check inexistent objects inexistent property. – tomsseisums Nov 25 '12 at 16:26
  • The answer is that the closest thing to `isset` that JavaScript offers is `.hasOwnProperty`. – I Hate Lazy Nov 25 '12 at 16:29
  • 1
    You could check each step separately, as in `typeof something` first, then `typeof something['deep']`, etc. Unfortunately you cannot create a function for this, because passing `something` would cause a `ReferenceError` as well. – pimvdb Nov 25 '12 at 16:30

2 Answers2

2

you could write a function who does check the object itself and the property:

function isset(obj, prop) {
  return typeof obj !== 'undefined' ? obj.hasOwnProperty(prop) : false;
}

you would call it like that:

myObj = {
  "myprop1": "myvalue1"
};

isset(myObj, "myprop1"); // returns true
isset(myObj, "anotherprop"); // returns false
isset(); // returns false

edit: to answer your question, no there is no native function who does that, you have to write it by yourself, if you want the object to be deeply checked (if somewhere inside the object the property exists). you could do it recursive. but i dont see any sense in doing it, because you dont know at which "level" that property exists (you could return it, but then you dont have a isset-function with an boolean-return-value)

hereandnow78
  • 14,094
  • 8
  • 42
  • 48
2

this should work if var is variable you have to check for..

  if (typeof(var) != 'undefined' && var != null ) {
       //do something
    }
Smita
  • 4,634
  • 2
  • 25
  • 32