In javascript is there a difference between using
if (foo.length > 0) {
//run code involving foo
}
and
if (foo) {
//run code involving foo
}
If so, could someone please explain the difference and an example where they would not be the same?
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.
The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.
The if statement allows you to control if a program enters a section of code or not based on whether a given condition is true or false. One of the important functions of the if statement is that it allows the program to select an action based upon the user's input.
if var: has the same effect as writing. if bool(var): (where bool is the built-in bool type which also acts as a constructor function for bool objects). If the value is already a bool (valued True or False) the meaning is clear -- bool(var) returns the same value.
Here's an example where they are not the same:
var x = [];
alert(x? 'yes' : 'no'); // displays "yes"
alert((x.length > 0)? 'yes' : 'no'); // displays "no"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With