1

When writing javascript or PHP for that matter I use two ways to write if statements.

Return as soon as possible

Below I try to end the function as soon as possible. If the value is not what I expect, return it. The benefit I see here is that I don't need {} and I don't need to nest anything.

function hello(value = null) {
  if(!value) return;

  console.log("I'm still here!");
  console.log("End of function");
}

Do something on match

In this case I don't return at all. Instead I do something if I get a "match". The upside here is that I don't need to return anything.

function hello(value = null) {
  if(value) {
    console.log("I'm still here!");
    console.log("End of function");
  }
}

So which is better? One of them or equally good?

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
  • 7
    I like the first because it keeps the indentation to a minimum, but this question is really going to collect opinions, which is not what Stack Overflow is about. – trincot Mar 11 '19 at 14:41
  • 1
    Note that a value can be "false" even if it's not `null`. – Some programmer dude Mar 11 '19 at 14:42
  • 1
    I'm also a fan of the first one. Otherwise you get into a stacked indentation sideways pyramid when you have more than one condition and some loops. But, again, opinion based - some dislike multiple exits of a function. – VLAZ Mar 11 '19 at 14:43
  • 1
    I don't believe there's a performatic difference, so what's more easy to understand would be my call – Lucas Noetzold Mar 11 '19 at 14:43
  • Even though it does not cost a lot, in terms of performance we should consider `branch prediction`. So, I would suggest to think about `misprediction cost`. Since it depends on your code, the answer may vary. – Onur Arı Mar 11 '19 at 14:44

0 Answers0