lundi 13 janvier 2020

Are "else" blocks redundant in function declarations? [closed]

Today, I noticed that I can write a function in two separate ways and get the exact correct answer. Of course, it's no wonder; there is a myriad of ways to solve a problem. But I feel like one of these two specific codes should be better―maybe more performant―than the other and their difference are not limited only to their shape and structure.

Let's say we have a function that decides whether its input is a number or not. Two of the ways you can do this are as follows.

function isNumber(inputNumber) {
  if (typeof inputNumber !== "number") {
    return 0; // is not number.
  } else {
    return 1; // is number.
  }
}

Or,

function isNumber(inputNumber) {
  if (typeof inputNumber !== "number") {
    return 0; // is not number.
  }

  return 1; // is number.
}

The second code is shorter but the first one looks more correct to me, semantically; Because it shows that return 1 is actually the result of "the first condition is not true."

Is it just a matter of taste? Does the second function definition actually more performant than the first one? Which solution would you prefer and why?

Aucun commentaire:

Enregistrer un commentaire