javascriptarraystypescriptconditional-statementstruthiness

Whats the difference between the following conditions in TypeScript?


if (!value || value.length<1) 
if (value.length<1)

What's the difference between the two conditions? Wouldn't it be same?


Solution

  • If value is null or undefined, the second if will throw an error stating that you can't access length of null / undefined.

    The first one prevents that, as it will only be accessing value.length if value is truthy. Otherwise, the first condition (!value) is satisfied, so the second one (value.length < 1) won't even be evaluated.

    const arr1 = null;
    const arr2 = [];
    
    // Satisfies first condition:
    if (!arr1 || arr1.length < 1) console.log('No values in arr1.');
    
    // Satisfies second condition:
    if (!arr2 || arr2.length < 1) console.log('No values in arr2.');
    
    // Breaks:
    if (arr1.length < 1) console.log('No values in arr1.');

    Anyway, that's not specific to TS, it's just how vanilla JS works.