javascript icon indicating copy to clipboard operation
javascript copied to clipboard

adding ternary operator along with example

Open sumn2u opened this issue 10 years ago • 4 comments

sumn2u avatar Apr 21 '15 09:04 sumn2u

@hshoff any opinions here?

goatslacker avatar Apr 27 '15 23:04 goatslacker

Let's just add an extra bullet to Conditional Operators & Equality under Use shortcuts. that says For readability, don't nest ternary operators.

(i realize there are fancier ways to write fizzbuzz)

// bad
for (var i = 1; i <= 16; i++) {
  var msg = i % 3 === 0 ? i % 5 === 0 ? 'FizzBuzz' : 'Fizz' : i % 5 === 0 ? 'Buzz' : '';
  console.log(msg || i);
}

// good
for (var i = 1; i <= 16; i++) {
  var msg = '';
  if (i % 3 === 0) {
    if (i % 5 === 0 {
      msg = 'FizzBuzz';
    } else {
      msg = 'Fizz';
    }
  } else if (i % 5 === 0) {
    msg = 'Buzz'
  } 
  console.log(msg || i);
}

// good
var superpower = isSuperman(user) ? 'flight' : 'none';

hshoff avatar Apr 28 '15 00:04 hshoff

Hello there,

This cases should be resolved too :

var y = a ?
  longButSimpleOperandB : longButSimpleOperandC;
var z = a ?
  moreComplicatedB :
  moreComplicatedC;

or

var z = a
  ? moreComplicatedB
  : moreComplicatedC;

cmalard avatar Nov 30 '15 01:11 cmalard

Related to #673.

ljharb avatar Jan 14 '16 18:01 ljharb