Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript testing .length and .length > 0

Tags:

javascript

I have some text in an object's property. I'm testing to see if the object's property has text in it to display; if it doesn't then I display "-" instead of just a blank. It doesn't seem like there's a difference between:

if (MyObject.SomeText && MyObject.SomeText.length) { ... }

if (MyObject.SomeText && MyObject.SomeText.length > 0) { ... }

Are there any edge cases where one syntax would be preferable to the other?

like image 810
frenchie Avatar asked Aug 16 '12 17:08

frenchie


People also ask

Is .length and .length 0 the same?

No, they are equivalent, if the length equals to 0 then it is valued as false .

Is array length 0 false?

Since the value of arr. length can only be 0 or larger and since 0 is the only number that evaluates to false , there is no difference.

What is length method in JavaScript?

The length function in Javascript is used to return the length of an object. And since length is a property of an object it can be used on both arrays and strings. Although the syntax of the length function remains the same, bear in mind that the interpretation of length varies between arrays and strings.


1 Answers

they give same result. Btw, if its "text", then if (MyObject.SomeText) is enough

like image 103
Eric Yin Avatar answered Oct 21 '22 01:10

Eric Yin