Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two JavaScript statements - are they equivalent?

Tags:

javascript

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.

like image 505
Haradzieniec Avatar asked Dec 20 '22 13:12

Haradzieniec


1 Answers

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.

like image 182
Bergi Avatar answered Dec 22 '22 01:12

Bergi