Haradzieniec
Haradzieniec

Reputation: 9340

Comparing two JavaScript statements - are they equivalent?

Are these two statements equivalent?

var var1 = var2 ? var2 : 0;

var var1 = var2 || 0;

Seems like yes, however I'm not sure.

var2 is (probably) defined above.

Upvotes: 4

Views: 82

Answers (3)

BoltClock
BoltClock

Reputation: 723598

Yes, they are equivalent. Both statements evaluate to var2 if and only if var2 is a truthy value (i.e. not zero, NaN, false, null, or the empty string).

Note that this assumes evaluating var2 has no side-effects, which applies in the vast majority of cases.

Upvotes: 4

Bergi
Bergi

Reputation: 664528

No, they're not:

> var i=0;
> with({ get var2() { return ++i; } }) {
>    var var1 = var2 || 0;
> }
> var1
1
> var i=0;
> with({ get var2() { return ++i; } }) {
>     var var1 = var2 ? var2 : 0;
> }
> var1
2

As you can see, the second one evaluates var2 twice. However, this is the only difference, and one that hardly matters for "normal" variables.

Upvotes: 5

Matt
Matt

Reputation: 3120

In this context they are identical in the sense that they both test the truthiness of var2.

Obviously though the ternary variant has more flavor to it should you want to test the variable for something other than whether or not the value is true.

Upvotes: 2

Related Questions