Pergunta

Apologies if this is a dupe, I've only seen an or || comparison.

If I want to set one variable's value based on a single condition, where b will always evaluate to true (not 0, null, undefined), why would I use the ternary operator a?b:c over the logical a&&b||c? They both appear to perform the exact same function, although tests on jsperf show the latter being slightly faster.

What is the purpose of the ternary operator if a very similar operation and syntax outperforms it at the same task? More curiously, what does it do that makes it slower?

Nenhuma solução correta

Outras dicas

What if you want to set a value conditionally to 0 or some non-zero value?

var x = condition() && 0 || 1;

That won't work, because 0 is falsy.

var x = condition() ? 0 : 1;

will work, because evaluation does not rely on the coerced boolean values.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top