In javascript I have a variable called length. When I try to test if (length)
javascript says it's true even though the value is Zero. What syntax should I use instead of if (length)
to test if there is a variable in there?
Asked
Active
Viewed 96 times
0

Robert Harvey
- 178,213
- 47
- 333
- 501

Mark Entingh
- 621
- 6
- 10
-
Did you already read about truthy and falsey in javascript? – WildCrustacean Mar 22 '13 at 20:00
-
What about `if (length > 0)`? – ulentini Mar 22 '13 at 20:00
-
4Cannot reproduce: http://jsbin.com/amagaz/1/edit – Quentin Mar 22 '13 at 20:00
-
1Since zero is falsy, I have to conclude that you're misrepresenting something. Either the code you're showing is not the real code, or length isn't really zero. In any case, if what you really want to do is check whether a variable contains something, see here: http://stackoverflow.com/q/5515310 – Robert Harvey Mar 22 '13 at 20:02
-
well what if length is undefined... then if (length > 0) doesn't work. – Mark Entingh Mar 22 '13 at 20:03
-
See the post I linked. – Robert Harvey Mar 22 '13 at 20:03
-
Perhaps `length` is the _string_ zero? `"0"` is truthy. – John Dvorak Mar 22 '13 at 20:03
1 Answers
1
That is how javascript works. To test if the variable is null or not you simply use this syntax if (length != null) ...

Vortex
- 663
- 6
- 7