Search code examples
javascriptvariablesbackbone.jseslintternary

Undefined variable when converting a ternary operator into traditional if statement


I'm using eslint to fix some coding standards in my backbone app. I have the following function in a view (simplified code):

getData: function(foo){
   var self = this;
   $.when(foo).then(function(){
      var doUpdate = false;

      self.makeAjaxRequest().done(function(data){
         self.trigger(doUpdate === false ? "foo" : "bar");
      });
   }
}

I'm needing to convert the ternary operator to a standard if statement. So I tried this:

getData: function(foo){
   var self = this;
   $.when(foo).then(function(){
      var doUpdate = false;

      self.makeAjaxRequest().done(function(data){
         self.trigger(function(){
            if(doUpdate === false) {
               return "foo";
            }

            return "bar";
         });
      });
   }
}

Unfortunately, it seems to cause issues in the code. I wonder if I'm referencing doUpdate correctly. Where have I gone wrong in this conversion?


Solution

  • In the original code, trigger is called with the value "foo" or "bar".

    In your updated code, trigger is called with a function.

    You never called the function you replaced the conditional with.

    I would keep the conditional version, but if you want to use your alternative instead, call your function:

    getData: function(foo){
       var self = this;
       $.when(foo).then(function(){
          var doUpdate = false;
    
          self.makeAjaxRequest().done(function(data){
             self.trigger(function(){
                if(doUpdate === false) {
                   return "foo";
                }
    
                return "bar";
             }());
    //        ^^--------------- Note
          });
       }
    }
    

    If you need to remove the conditional, though, I wouldn't do it that way. Instead:

    getData: function(foo){
       var self = this;
       $.when(foo).then(function(){
          var doUpdate = false;
    
          self.makeAjaxRequest().done(function(data){
             var triggerWith;
             if (doUpdate === false) {
                triggerWith = "foo";
             } else {
                triggerWith = "bar";
             }
             self.trigger(triggerWith);
          });
       }
    }
    

    Side note: Unless you have a real need to specifically check for false and not the various other falsy values, which doesn't appear to be the case in that code, just if (!doUpdate) rather than if (doUpdate === false) is the usual way.