문제

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?

올바른 솔루션이 없습니다

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top