Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  97] [ 2]  / answers: 1 / hits: 49682  / 12 Years ago, tue, august 21, 2012, 12:00:00

I'm having an interesting issue that I'm sure is easily explained, but the explanation is eluding me.



An undefined or null object in javascript is equal to false.



var x;
alert(!x); //returns true
alert(x==true); //returns false


What about an empty array object? Is that the equivalent of true or false?



var x = [];
alert (x==true); //returns false
alert (!x); //returns false


If it is equivalent to true, how do I check if it's non-empty? I was hoping to do



if (!x) {
//do stuff
}


I tried checking x.length, but I'm using this object as a map:



var x = [];
alert(x.length); //returns 0
x.prop = hello;
alert(x.length); //still returns 0


How can I check if my map is empty?


More From » javascript

 Answers
23

Little confused as you seem to be mixing objects and arrays in your question. Hopefully this might help clear it up for you.



An empty array evaluates to true:



!![] //true


But integer 0 evaluates to false, so you can do:



!![].length //false


So:



if([].length) {
//array has 1 element at least
} else {
//array has 0 elements
}


However you do seem to be getting arrays and objects confused. In JavaScript, we have objects:



var x = {};
x.foo = bar;
x.baz = 2;


And we have arrays:



var x = [];
x.push(foo);
x.length //1


You can't do what you do in your opener:



var x = []; //x is an array
x.foo = bar; //can't do this on an array
x.length; // 0

[#83504] Monday, August 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shekinah

Total Points: 699
Total Questions: 112
Total Answers: 110

Location: Philippines
Member since Sat, Jul 11, 2020
4 Years ago
;