Search code examples
javascriptjqueryajaxfirefoxternary

Ternary operators in AJAX initialization not setting appropriately


I'm working with some AJAX calls, which connect properly, however if I attempt to use a ternary operator in the initialization of the call, the operator does not set properly. Specifically, I'm trying to dynamically set the async parameter. The AJAX call refuses to accept the ternary version of the async unless it's specified beforehand. This is specific to Firefox. Here's an example:

Server receives the async call as true, regardless if I specify the async = false;.

function(url, type, async) {
    $.ajax({
        url: url,
        type: type,
        async: async ? async : true
    });
}

Works correctly:

function(url, type, async) {
    var async = async ? async : true;
    $.ajax({
        url: url,
        type: type,
        async: async
    });
}

Although the code is working when I specify it beforehand, I do not understand why a ternary operator won't work in this situation. I would love an explanation as to why it is required to be specified beforehand and not in the call itself.

Thank you, Ben


Solution

  • Your line

    async: async ? async : true
    

    ...says: If async is truthy, use async; otherwise, use true. So of course it's always truthy.

    If your goal is to default to async: true when async isn't given at all, do this:

    async: typeof async === "undefined" ? true : async
    

    That will use the value of async if it's not undefined, or true if it is.


    All due respect, I don't think the second version does anything differently to the first version, I think that must be observational error. This code emulates what you're doing, and always shows obj.bar as being true:

    jQuery(function($) {
    
      function foo1(bar) {
        var obj = {
          bar: bar ? bar : true
        };
        display("(1) obj.bar = " + obj.bar);
      }
    
      function foo2(bar) {
        var bar = bar ? bar : true;
        var obj = {
          bar: bar
        };
        display("(2) obj.bar = " + obj.bar);
      }
    
      foo1(false);
      foo1(true);
      foo2(false);
      foo2(true);
    
      function display(msg) {
        $("<p>").html(String(msg)).appendTo(document.body);
      }
    });
    

    Live copy | source

    (It's probably worth noting that the var part of the var async in your second example — and the var bar in my emulation of it — is ignored. No var is created, the argument is used directly.)