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

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

Danziger
  • 19,628
  • 4
  • 53
  • 83

3 Answers3

2

No, they are absolutely different.

!value

this checks for whether an item is present and it is not undefined, but ![] and also ![3] this is always false. basically it checks for presence.

and even [] is always true.

length

calculates the no of elements inside that array and it is purely applied to array.

for [] , value.length<1 this returns true.

Arun Kumar
  • 355
  • 3
  • 10
0

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.

Danziger
  • 19,628
  • 4
  • 53
  • 83
0

Quick way to understand is you cannot access length property of an undefined array. So the second if condition will throw an error akin to Cannot access property 'length' of undefined.

The first if condition however checks if the array is defined. So it won't throw any error.

Typescript contains a native way of doing this check using a "safe navigation operator" or optional chaining operator ?.. So in TS, you could simply do

if (value?.length < 1) { }

It is equivalent to JS

if ((value === null || value === void 0 ? void 0 : value.length) < 1) { }
ruth
  • 29,535
  • 4
  • 30
  • 57