Could someone explain what's happening here? I'm trying to use the javascript !!
(double-bang) operator as described here in conjunction with HTML5 local storage (I'm storing 0 and 1 values and testing for truthiness, but I also need a missing key to be false, hence the undefined at the start.
Although it echos to the console as false when typecast, it doesn't in the 'if' statement.
var foo = undefined;
// outputs undefined
console.log(foo)
// typecast to non-inverted boolean
console.log(!!foo);
if (!!foo) {
console.log("If was false before, why won't this execute?");
} else {
console.log("It didn't work");
}
Produces:
undefined
false
It didn't work
http://jsfiddle.net/YAAA7/
(Chrome v 23.0.1271.97 & Firefox 16.0.1, OS X 10.8.2)
Edit - corrected code:
(The previous 'if' statement was just evaluating as false, so that branch would never run.)
var foo = false;
// outputs undefined
console.log(foo)
// typecast to non-inverted boolean
console.log(!!foo);
if (!!foo == false) {
console.log("Matches for foo undefined, foo = 0 and foo = false");
} else {
console.log("Matches for foo = 1 and foo = true");
}