I wonder how this two are different ?
var hello = foo?foo:bar;
vs
var hello = foo || bar;
Can you explain this ? and some case example ? or both are same ?
PS : foo/bar should be all like string / int / obj / boolean...
I wonder how this two are different ?
var hello = foo?foo:bar;
vs
var hello = foo || bar;
Can you explain this ? and some case example ? or both are same ?
PS : foo/bar should be all like string / int / obj / boolean...
The ? :
is called the conditional operator It takes three arguments (which is why it's sometimes called the "ternary" operator): Something to test, something to return if the test is truthy, and something to return if the test is falsey.*
The second is JavaScript's curiously-powerful logical OR operator. It accepts two arguments. It evaluates the first operand and, if that's truthy, returns it; if the first is falsey, it evaluates and returns the second operand.
So the difference between those two is this: With the conditional operator, foo
may be evaluated twice (if it's truthy). With the ||
, foo
is only evaluated once. It doesn't really matter if foo
and bar
are just simple variable references, but consider:
var hello = foo() ? foo() : bar();
// vs
var hello = foo() || bar();
You can see how it matters how many times foo()
is evaluated, if it does any significant work or has any side effects.
(* So what are "truthy" and "falsey" values? The "falsey" values are 0
, ""
, NaN
, undefined
, null
, and of course false
. Everything else is "truthy".)