Daniel van Dommele
Daniel van Dommele

Reputation: 550

simplify if .. else in javascript

my mind is blank and I can't think of the solution...

I have the following code:

if (onlySelected === true) {
    if (r.selected == true) {
        result.push(pushValue);
    }
}
else {
    result.push(pushValue);
}

how can I simplify this code into this:

if (condition) { result.push(pushValue) } 

Upvotes: 0

Views: 200

Answers (6)

TrL
TrL

Reputation: 30

Hm, this is what I made it to.

onlySelected === !0 ? r.selected == 1 && result.push(pushValue) : result.push(pushValue)

Upvotes: 0

loganfsmyth
loganfsmyth

Reputation: 161657

Try this:

if (!onlySelected || r.selected){
    result.push(pushValue);
}

or this if you absolutely need the type equality and not just truthiness:

if (onlySelected !== true || r.selected){
    result.push(pushValue);
}

Upvotes: 8

Ian Routledge
Ian Routledge

Reputation: 4042

I think this would work:

if(!onlySelected || (onlySelected && r.selected))
    result.push(pushValue);

Upvotes: 0

d4rkpr1nc3
d4rkpr1nc3

Reputation: 1827

if( (onlySelected === true && r.selected === true) || 1) {
    result.push(value)
}

Upvotes: 0

MaxArt
MaxArt

Reputation: 22647

(!onlySelected || r.selected) && result.push(pushValue);

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

if(onlySelected === false || r.selected == true) {
    result.push(pushValue);
}

Upvotes: 0

Related Questions