if (!value || value.length<1)
if (value.length<1)
What's the difference between the two conditions? Wouldn't it be same?
if (!value || value.length<1)
if (value.length<1)
What's the difference between the two conditions? Wouldn't it be same?
On
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.
On
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) { }
If
valueisnullorundefined, the secondifwill throw an error stating that you can't accesslengthofnull/undefined.The first one prevents that, as it will only be accessing
value.lengthifvalueis truthy. Otherwise, the first condition (!value) is satisfied, so the second one (value.length < 1) won't even be evaluated.Anyway, that's not specific to TS, it's just how vanilla JS works.