William Turrell
William Turrell

Reputation: 3326

Boolean operators in if statement not working

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");
}​

http://jsfiddle.net/YAAA7/1/

Upvotes: 1

Views: 6346

Answers (2)

user1637281
user1637281

Reputation:

That is expected behavior. If you double not false, you get false. This ,!l is a not operator. This ,!!, is two not operators. The double not operator is sometimes used to cast to the Boolean type.

! false === true
!! false === false

Upvotes: 5

kannanrbk
kannanrbk

Reputation: 7134

var foo = undefined;

foo will return true. Because, in JavaScript "", undefined, 0, NaN, false and null are considered falsey values.

http://www.mapbender.org/JavaScript_pitfalls:_null,_false,_undefined,_NaN .

From your code:

var foo = undefined; //false

console.log(!!foo); // !!foo = false;

if(!!foo) { //false
  console.log("It will not come because the condition fails");
}else{
    console.log("Else Part");
 }

Upvotes: 1

Related Questions