Mr T
Mr T

Reputation: 1000

Turning a ternary operator into if else statement on return

I'm currently using a ternary operator as follows:

return $scope.productWithEAN(EAN).then(function(product) {
   return (product) ? product : $scope.createProduct(productID, name);
  });
});

I want to now point to a function if return (product) ? product

I believe that this is best done with an if else statement. I have created this, however I am getting an unexpected return token:

return $scope.productWithEAN(EAN).then(function(product) {
  if (return (product) ? product) {
      console.log("product is here");
      //$scope.checkOrUpdateProduct;
    },else {
      console.log("product not here");
      //$scope.createProduct(productID, name);
    };
  });
});

Is there a better way of doing this?

Upvotes: 0

Views: 188

Answers (1)

baao
baao

Reputation: 73231

You can't use if (return ...). If you want to rewrite it to a if else statement, you can use this:

return $scope.productWithEAN(EAN).then(function(product) {
    if (product) {
        console.log("product is here");
        return $scope.checkOrUpdateProduct();
    } 
    console.log("product not here");
    return $scope.createProduct(productID, name);
});

Note that there isn't the need of if else, if the if condition meets, the else part will never be reached as we return inside the if. So you can just return inside the if and don't need an else thereafter.

Upvotes: 2

Related Questions