ternary operator for 3 conditions code example

Example 1: ternary operator for multiple conditions

String year = "senior";
if (credits < 30) {
  year = "freshman";
} else if (credits <= 59) {
  year = "sophomore";
} else if (credits <= 89) {
  year = "junior";
}
Contrast this with the ternary operator:

String year = credits < 30 ? "freshman" : credits <= 59 ? "sophomore" : credits <= 89 ? "junior" : "senior";

Example 2: Ternary Operator

condition ? expression-if-true : expression-if-false;

function findGreater(a, b) {
  return a > b ? "a is greater" : "b is greater";
}

Example 3: ternary operator

if ($scope.SearchSalesOrderAndCompanyName !== undefined && $scope.SearchSalesOrderAndCompanyName != null ) {
            SearchCriteria += " AND [SalesOrderNo] LIKE '%" + $scope.SearchSalesOrderAndCompanyName + "%' OR ([SO].[CompanyNameOnBill] LIKE '%" + $scope.SearchSalesOrderAndCompanyName + "%')";
        }
        if ($scope.FromDate !== undefined && $scope.FromDate !=null) {
            SearchCriteria += " AND [SO].[SalesOrderDate] LIKE '%" + $scope.FromDate + "%'";
        }

Example 4: The conditional (ternary) operator with three condition

String year = credits < 30 ? "freshman" : credits <= 59 ? "sophomore" : credits <= 89 ? "junior" : "senior";

Tags:

C Example