How to check undefined variable in a ternary operator?

后端 未结 3 1356
别那么骄傲
别那么骄傲 2021-02-14 17:02

I have an issue with ternary operation:

let a = undefined ? \"Defined!\" : \"Definitely Undefined\",
    b = abc ? \"Defined!\" : \"Definitely Undefined\", // Re         


        
相关标签:
3条回答
  • 2021-02-14 17:08

    What is the best and short way to check if abc is undefined before accessing its properties as well as assign blank object {} if undefined?

    And you said that

    I am currently using (typeof abc !== "undefined")

    Looks like you have abc defined and the value is undefined.

    You can try doing

    var a = abc || {};
    console.log(a);
    
    0 讨论(0)
  • 2021-02-14 17:12

    while b and c throw ReferenceError when abc is undefined

    So abc isn't just undefined, it's undeclared. There's a big difference there.

    If you need to handle abc being undeclared, the only safe way to do that (without try/catch) is with typeof:

    typeof abc === "undefined"
    

    That will be true, without error, if abc is an undeclared identifier. It will also be true if abc is declared and contains the value undefined.

    What is the best and short way to check if abc is undefined before accessing its properties as well as assign blank object {} if undefined?

    Probably using var to ensure it's declared:

    var abc = abc || {};
    

    Duplicate var declarations are not errors (duplicate let declarations are). So with the above, if abc is undeclared, it gets declared with the initial value undefined and we assign it {}. If it's declared, we replace its value with {} if it's falsy. But, if it may or may not be declared with let or const, then the above will throw an error as well.

    So to handle the case where it may or may not be declared with let or const, we need a different variable entirely:

    let ourabc = typeof abc === "undefined" || !abc ? {} : abc;
    

    That sets ourabc to {} if abc is undeclared or if it contains a falsy value. Since all non-null object references are truthy, and you've said you want to access object properties, that's probably the shortest way.

    0 讨论(0)
  • 2021-02-14 17:18
       state = (typeof state !== "undefined") ? state : '';
    

    This way you can check undefined variable in a ternary operator.

    0 讨论(0)
提交回复
热议问题