简体   繁体   中英

javascript ternary condition operation

I want to achieve the below logic using javascript ternary operation. Is this possible?

if(condition1){
    console.log("condition1 pass");
} else if(condition2){
    console.log("condition2 pass");
} else{
    console.log("It is different");
}

Sure, you just have to have one ternary inside another:

Put the else if condition inside the : part.

console.log(
    condition1
        ? "condition1 pass"
        : condition2
            ? "condition2 pass"
            : "it is different"
);

It's best not to do this as the syntax is easily mistakable and slim, you could, however, move this to a function or IIFE if it's already inside a function and return the result directly to reduce a loop:

function testCondition(condition1, condition2){
    if(condition1){
        return "condition1 pass";
    } else if(condition2){
        return "condition2 pass";
    }
    return "It is different";
}

var conditionalPass = (function(condition1, condition2){
    if(condition1){
        return "condition1 pass";
    } else if(condition2){
        return "condition2 pass";
    }
    return "It is different";
})(condition1, condition2);

Yes, it is. Using the following logic:

var output = ((condition1) ? 'condition1 pass' : ((condition2) ? 'condition2 pass' : 'It is different'));

console.log(output)

It is possible but not recommended:

console.log(condition1? "condition1 pass": (condition2? "condition2 pass": "It is different"));

As you can see the code is very difficult to read.

It's possible, but recommended.

console.log(
    condition1?//if
        "condition1 pass":
    condition2?//else if
        "condition2 pass"://else
        "It is different"
)

As you can see, it's very easy to read it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM