Truthiness in Javascript
Here's a function we will use. It should already be defined in the
Javascript console.
function truthy(x) {
return (x) ? true : false;
}
Most values behave how you would expect
For example...
These values are all truthy
> true
> 1
> 'false'
> Infinity
> -Infinity
These values are not truthy
> false
> 0
> NaN
> undefined
> null
Things that make you go, "hmm"
> ''
> -1
> {}
> []
> [0]
> [null]
TL;DR
Always, always use strict equals.
Otherwise....
A Test
truthy([]); // => true
truthy([] == false); // true
But wait...
truthy(null); // => false
truthy([null]); // => true
truthy([null] == false); // ?
And...
truthy(0); // => false
truthy([0]); // => true
truthy([0] == false); // ?
And...
truthy(undefined); // => false
truthy([undefined]); // => true
truthy([undefined] == false); // ?
But there's this...
truthy([undefined] == [undefined]);
truthy([undefined] == undefined);
And this...
truthy([null] == [null]);
truthy([null] == null);
truthy([null] == 0);
truthy([null] == '');
truthy([null] == false);
And this...
truthy([0] == [0]);
truthy([0] == 0);
truthy([0] == '0');
And this...
truthy([Infinity] == [Infinity]);
truthy([Infinity] == Infinity);
The concept of truthiness in Javascript is not that hard to deal with.
But no matter what you do, always, always, always use strict equals.
Because == can make you gaggy.