2

how can i check a js chain var exists ? any simple method to check ,or usign jquery
please see codes bellow:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    // how can i check a var exists ?
    // the code bellow will return undefined
    // a is undefined
        // a.b is undefined --- when a exists, then I need to check a.b
            // a.b.c is undefined  ...
                // a.b.c.d is undefined
    // sometimes I need to check if some property of an object exists or is true, and I don't even know the object exists or not
    // how can I check it then ?
    if(a.b.c.d){
        alert('yes');
    }
</script>
mingfish_004
  • 1,385
  • 2
  • 18
  • 26

6 Answers6

6
if((typeof a !== 'undefined') && (typeof a.b !== 'undefined') && (typeof a.b.c !== 'undefined') && (typeof a.b.c.d !== 'undefined')){
        alert('yes');
}

By using && (AND condition) the condition checking immediately stops when a single condition fails. Therefore if a in not defined then it will not go for other checkings.

With ES2020 (Chrome 80+, Firefox 74+) you can do optional chaining:

if(a?.b?.c?.d) alert('yes');
DJ Ramones
  • 823
  • 1
  • 5
  • 11
gurudeb
  • 1,856
  • 22
  • 29
  • No need to be so wordy. – Ethan Brown Feb 08 '14 at 06:26
  • agreed... but its good to go for type checking... gives that extra bit of added confirmation :) – gurudeb Feb 08 '14 at 06:28
  • In this case, it actually doesn't. If you wanted to ensure that the things were _objects_ (as opposed to atomics like numbers or booleans), you would instead use `typeof a === 'object'`. `typeof a !== 'undefined'` will actually allow sillier things than just using coercion to false. – Ethan Brown Feb 08 '14 at 06:30
  • 1
    The only way your method would provide different results is in the following case: `var a = 0;`. Mine would not proceed, but yours would. However, since literal numbers box to object Number (which is immediately discarded), there's no way you could have `a.b`. So, for all practical purposes, mine is just as "safe", and a lot easier to read. Plus, it's idiomatic. – Ethan Brown Feb 08 '14 at 06:32
  • You can safely use the typeof operator on undefined variables... therefore a.b if not defined will fail as expected – gurudeb Feb 08 '14 at 06:40
  • I'm aware of that gurudeb, that was not my point: my point is there is no case in which your answer is any safer than mine. Well, except for jfriend00's excellent comment on my post, which I corrected. – Ethan Brown Feb 08 '14 at 07:02
  • Ok Ethan, no problem. Yes the point jfriend00 raised is a valid point where your first code would have failed under that condition. So your second code is correct as you have added the type checking on the last condition (leaf condition). However my initial code already caters to that leaf condition. So both our codes work fine. :) – gurudeb Feb 08 '14 at 07:52
5

Using if conditions can become clumsy as the level of nesting grows. Use this utility function which works perfectly fine for any level of nested objects.

function checkExists( val, names ) {
    names = names.split( '.' );    
    while ( val && names.length ) { val = val[ names.shift() ]; }    
    return typeof val !== 'undefined';
}

Usage

if ( checkExists( a, 'b.c.d' ) ) {
    // operate on a.b.c.d
}

Live demo: http://jsfiddle.net/DWefK/

Shiva Avula
  • 1,836
  • 1
  • 20
  • 29
4

You can just use boolean operators:

if(a && a.b && a.b.c && a.b.c.d){
    alert('yes');
}

In the comments, it was pointed out that if a.b.c.d is "falsy" (0, false, an empty string, or an empty array), the alert will not be printed, even though the property exists. So an ironclad way to do this would be:

if(a && a.b && a.b.c && typeof a.b.c.d !== 'undefined'){
    alert('yes');
}

Thanks to short-circuit evaluation, this will not throw an error.

Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
  • 1
    Note: you have to be careful with the last variable in the chain because it can have a valid, but falsey value such as `false`, `0`, `""`, `null`, etc... so `if (a.b.c.d)` doesn't tell you whether `.d` exists only if it's truthy or not. To tell the difference between falsey values and `undefined`, one needs to check for `undefined` explicitly on the last item in the chain. – jfriend00 Feb 08 '14 at 06:55
0
if (typeof a !== 'undefined' && a.b !== undefined && a.b.c !== undefined && a.b.c.d !== undefined)
alert('yes')
Zhong Xu
  • 17
  • 1
0

I think the best way to do this is to catch the error

try {
    if (a.b.c.d) {
        alert('yes');
    }
} catch (error) {}
SlimDeluxe
  • 733
  • 8
  • 18
  • try/catch is not self explanatory, while a semantic function isExists makes the code much readable not to mention shorter. – hamecoded Jan 02 '18 at 15:57
0

This function will work for checking that a.b.c is defined as well as checking something like a.b[1].d

let isDefined = (baseObject, varChian) => {
    try{
        if(typeof varChian != "undefined"){
            return eval(`baseObject.${varChian} != undefined`);
        }
        return typeof baseObject != "undefined";
    }catch(e){
        return false;
    }
}

Then you can call it by

isDefined(a, "b[1].c");
isDefined(a);
isDefined(a, "b.c")
cford 50
  • 96
  • 1
  • 4