Search code examples
javascriptternary

Seemingly redundant ternary operators in javascript


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.


Solution

  • 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) { 
      // ...
    }