2

The following is common code floating around online that checks if cookies are enabled in a particular browser:

var cookieEnabled = (window.navigator.cookieEnabled) ? true : false;

if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled) {
    document.cookie = "testcookie"
    cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false
}

if (!cookieEnabled) {
    // do some work
}

Why are the first and fifth lines ternary statements? Does

var cookieEnabled = (window.navigator.cookieEnabled) ? true : false;

catch some case that the following wouldn't?

var cookieEnabled = (window.navigator.cookieEnabled);

The same goes for the fifth line.

rjkaplan
  • 3,138
  • 5
  • 27
  • 33

2 Answers2

3

The ternary statement at the first line is useful in that it coverts a possible non-boolean value into a boolean one. Consider the following code

window.navigator.cookieEnabled = "evil people do this";

The above is legal and as the value says evil people do do this. Without the ternary statement the following code wouldn't execute as expected

if (cookiesEnabled === false) { 
  // ...
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • @Andre other than being shorter is there an advantage gained by using `!!`? Genuinely asking. Curious if it's a style issue or a functional reason I'm missing – JaredPar Jul 06 '12 at 20:40
  • @JaredPar: I see! And what if I were to use `if (!cookiesEnabled)`? Would that mean that I could be rid of the ternary statements? – rjkaplan Jul 06 '12 at 20:40
  • @JaredPar AFAIK no, there's no other benefit – Ortiga Jul 06 '12 at 20:42
  • 1
    Actually, the == operator compares the implicit boolean values, which ternary statement does not change. The only case where explicitly converting to boolean is really necessary is if you use the === operator (or do other type checks). – oxc Jul 06 '12 at 20:42
  • @oxc oops I missed that they used a `==` vs. a `===`. Looks like the current version uses neither ... I'll update my answer to make sense given `===` – JaredPar Jul 06 '12 at 20:54
2

To be precise:

(window.navigator.cookieEnabled) ? true : false

is equivalent to:

!!window.navigator.cookieEnabled

However:

(document.cookie.indexOf("testcookie") != -1) ? true : false

can be simply replaced by:

document.cookie.indexOf("testcookie") != -1

Finally:

cookieEnabled == false

can be changed to:

!cookieEnabled

So what's the problem with the first case? In JavaScript non-zero numbers, non-empty strings, etc. evaluate to true. So if(window.navigator.cookieEnabled) passes for cookieEnabled being equal to "foo" and 42 as well. If you really want to have a variebale of boolean type, you must negate it twice.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674