Use if-else or if only to assign a single value?

I'm curious for the codes below:

Code 1:

var myValue = 10;
if(isBlocked)
  myValue = 20;

Code 2:

var myValue;
if(isBlocked)
  myValue = 20;
else
  myValue = 10;

Both must do the same. But I prefer Code 1, as this obviously requires fewer lines. Is it better to use code 1 to assign a single value?

EDIT

Thanks guys to remind me of the "triple operator". Before closing the message, I would like to ask: "Rate the assignment", similar to "Calculate the expression else"? (Performance)

+4
source share
4 answers

Yes, code 1 is better, a few lines do the same.

You can do this shortly with the ternary operator

var myValue = isBlocked ? 20: 10;
+3

:

var myValue = 10;

if (isBlocked) {
    myValue = 20;
    }

- , .

:

myValue 10, , if statement ( - ), myValue, , 10.

+2

1, , , undefined myValue

2 , if , myValue undefined. 1 .

*** UPDATE if , myValue undefined, , else, myValue, , , .

+1
source

Both are beautiful! It all depends on whether you need to add additional comparisons in the future. If yes, use code 2, if not use code 1.

0
source

All Articles