l2aelba
l2aelba

Reputation: 22217

Shorthand if/else statements : foo?foo:bar vs foo || bar

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...

Upvotes: 1

Views: 1075

Answers (2)

Idrab
Idrab

Reputation: 101

The 'foo' is a placeholder commonly used in programming and documentation in the context of 'URL'

Upvotes: -1

T.J. Crowder
T.J. Crowder

Reputation: 1075567

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".)

Upvotes: 6

Related Questions