top | item 20310322

(no title)

baolongtrann | 6 years ago

I agree with the 1st pattern.

The 2nd one, there's a caveat about space/GC here.

The 3rd one depends a lot on the situation.

4th one is too obvious for it to be called a pattern, but I agree with it.

5th one is, meh, not really easy to read. I prefer his "bad" example. It could be less verbose, e.g,

if (!conditionA) result = "Not A"

else if (conditionB) result = "A & B"

else result = A

discuss

order

foota|6 years ago

Personally, I'd prefer to go with early return, I think. Depending on what the conditions mean semantically.

It would be:

  if (conditionA && conditionB) {
    return "A & B"
  }

  if (conditionA) {
    return "A" 
  } else {
    return "Not A"
  }
  
  return "neither A nor B"
I think this comes from a general dislike of more than one else on an if and a dislike of nesting.

masswerk|6 years ago

Regarding nested ternaries, while not recommended, short circuit evaluations may be even more readable:

return ( (cA && cB && "A & B") || (cA && "A") || (cB && "B") || "neither" );

foota|6 years ago

Quick, it's another case of Javsacript Stockholm Syndrome!

scns|6 years ago

Same concerns about #2 here, prettier code but worse performance, Form over Function.