I noticed something today about Arrays in JavaScript that struck me as a bit odd. I imagine there is an easy explanation that will make perfect sense when I hear it, but until then I thought I would ask the community.

If I use an Array as the sole component of a conditional statement, the statment evaluates to true whether the array is empty or not. However, if the conditional statement is loosely comparing (==) the array to a truthy value, then it evaluates to false, again whether its empty or not. I created a Fiddle to show what I mean: http://jsfiddle.net/dcdruck/X6L8m/11/

Would someone please try to explain to me why an Array is considered truthy on its own but not when compared to another truthy value?

Recommended Answers

All 2 Replies

function isTruthy(a,b) { if (a) setTrue(b); else setFalse(b); };

This is not checking whether the array is empty, it's simply checking if that object/variable exists.

function isTrue(a,b) { if (a === true) setTrue(b); else setFalse(b); };

This outputs false because you're comparing the array object to the primitive value true.

function isTruish(a,b) { if (a == true) setTrue(b); else setFalse(b); };

This is a little more complicated, though I think the top answer on this StackOverflow question explains it better than I could.

function isTruthyAnd(a,b) { if (a && true) setTrue(b); else setFalse(b); 

Like the first function, you're only testing whether the variable/object exists. If you put if (true) as a check for anything, it will always be true.

I guess that sorta makes sense. I think it struck me as odd that the array's existence is being evaluated in the first one instead of the array itself being evaluated. I would have expected if (someArray) and if (someArray == true) and if (someArray == 1) all to evaluate the same, but I was wrong. I would have expected Javascript to do the same internal conversion on someArray to convert it to a scalar value (like Array.prototype.toString) regardless of what else was in the conditional statement.

Thanks for the input and the link! I'm marking this as solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.