DEV Community

Amr Ataa
Amr Ataa

Posted on

Use “? … : …” instead of “if… else…”

Many times simple conditional judgments do not need to use “if”.

Image description

Top comments (4)

Collapse
 
frankwisniewski profile image
Frank Wisniewski

I don't like these if else constructions either
and work like this:

let n = 18;
let result = 'odd Number';
if (n % 2 == 0){
  result = 'even Number';
}
Enter fullscreen mode Exit fullscreen mode

short, then short...

let result = `${n % 2 === 0 ? 'even' : 'odd'} number`;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
amrataabdallh profile image
Amr Ataa

It's awesome syntax.

Collapse
 
alterview profile image
Gert Wierbos

I ALWAYS go for the longer "IF" statements because of readability... :)

For me, readability of code is more important than saving a few lines of code.

Collapse
 
amrataabdallh profile image
Amr Ataa

First code for correctness, then for clarity (the two are often connected, of course!). Finally, and only if you have real empirical evidence that you actually need to, you can look at optimizing. Premature optimization really is evil. Optimization almost always costs you time, clarity, maintainability. You'd better be sure you're buying something worthwhile with that.

Note that good algorithms almost always beat localized tuning. There is no reason you can't have code that is correct, clear, and fast. You'll be unreasonably lucky to get there starting off focusing on `fast' though.