Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript complex One-liner if statements

Tags:

javascript

First time saw such ternary expressions:

var somevar = b1 ? b2 ? b3 : b4 : b5 ? b6 : b7 ? b8 : b9 ? b10 : b11

Having a hard time understanding and converting it to:

if (b1) {
} else if (bx) {
}

I've looked everywhere and can't seem to find the answer to this.

like image 846
AamirR Avatar asked Dec 18 '22 21:12

AamirR


1 Answers

Just add parentheses.

var somevar = (b1 ? (b2 ? b3 : b4) : (b5 ? b6 : (b7 ? b8 : (b9 ? b10 : b11))))

I.e.

if (b1) {
  if (b2) {
    b3
  } else {
    b4
  }
} else {
  if (b5) {
    b6
  } else {
    if (b7) {
      b8
    } else {
      if (b9) {
        b10
      } else {
        b11
      }
    }
  }
}

Or to make it shorter.

if (b1) {
  if (b2) {
    b3
  } else {
    b4
  }
} else if (b5) {
  b6
} else if (b7) {
  b8
} else if (b9) {
  b10
} else {
  b11
}

Start from the far right. whenever you find a ? b : c add parentheses around it.

For example:

 a ?  b ? c : d  : e

 a ? (b ? c : d) : e

(a ? (b ? c : d) : e)
like image 112
Louay Alakkad Avatar answered Dec 21 '22 11:12

Louay Alakkad