Comparing two JavaScript statements - are they equivalent?

Are these two statements equivalent?

var var1 = var2 ? var2 : 0;

var var1 = var2 || 0;

It seems yes, but I'm not sure.

var2 (possibly) is defined above.

+4
source share
3 answers

No, it is 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 is rated var2twice. However, this is the only difference, and it hardly matters for the "normal" variables.

+5
source

Yes, they are equivalent. Both operators evaluate to var2if and only if it var2is a true value (i.e., non-zero, NaN, false, null, or an empty string).

, , var2 , .

+4

In this context, they are identical in the sense that they both verify credibility var2.

Obviously, the triple option has more taste if you want to check the variable for something else, besides whether the value is true.

+2
source

Source: https://habr.com/ru/post/1546163/


All Articles