Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between if (var.length >0){} and if (var){}

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?

like image 872
mazlix Avatar asked Jun 18 '11 04:06

mazlix


People also ask

Is array length the same as array length 0?

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.

Does an empty array have a length of 0?

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.

What is if variable in C?

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.

What does if var mean in Python?

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.


1 Answers

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"
like image 153
Mark Eirich Avatar answered Oct 11 '22 16:10

Mark Eirich