skip to Main Content
@Input() a: number;

// Check of null or undefined
if (a)
  // do stuff

With the usual check, the value 0 will also be considered as false and the variable will not pass the if.

There is already a lot of questions around this but I could not find anything that handles the value zero.
Is there anything like the a?.b of typescript but for simple type?

2

Answers


  1. Chosen as BEST ANSWER

    The obvious solution is the verbose (when you need to check multiple values it quickly becomes crowded in your condition).

    if (a !== undefined && a !== null)
      // do stuff
    

    I also thought of this, a bit shorter but less obvious to read

    if (a || a === 0)
      // do stuff
    

  2. Keeping the code from becoming crowded is a good goal. You can define your own functions, like so:

    function isBlank(s) {
        return (undefined === s || null === s || "" == s.trim());
    }
    function isZero(s) {
        return (!isBlank(s) && "0" == s.trim());
    }
    

    Your original code block changes as follows, and is just as easy to read:

    // Check of null or undefined
    if (isZero(a))
      // do stuff
    

    For more information on the falsy values in JavaScript, here are a few good resources:

    https://stackabuse.com/javascript-loose-equality-operator-vs-strict-equality-operator/

    All falsey values in JavaScript


    To play around with some additional values:

    https://jsfiddle.net/Lr98kzsa/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search