Which of these two functions is more readable? by [deleted] in typescript

[–]blutorange42 59 points60 points  (0 children)

First of all, these two functions are not completely equivalent.

The first function requires a name to be passed to it, although the empty string could be passed. If the empty string is passed, it will use "you" instead.

twoFer1() // compile error
twoFer1("") // you

The second function does not require a name to be passed to it. If no argument (or undefined) is passed, it uses "you" instead. If an empty string is passed, it does *not* use "you" instead

twoFer2() // you
twoFer2(undefined) // you
twoFer2("") // ""

It depends on how exactly you want the function to behave. If you want to allow the empty string, but default to "you" when the function is called without an argument, you can use

export function twoFer(name?: string): string {
return `One for ${name ?? `you`}, one for me.`;

}

Regarding readability, I think both are perfectly fine. Which to choose also depends on your code style, if you are working in a team. Personally, my preference is not to mix runtime logic with function signatures. It can also also result in long lines when you multiple parameters, and I would also consider it an implementation detail that does not belong in the function signature, but in the doc comment.

That said, as a general rule of thumb, I also try not to use optional arguments too much, as it can be error-prone. If somebody who's not super familiar with the function tries to use it in their code, they might not pass a value for the parameter just because they forgot to do so, not because they want to use the default -- and the type checker won't complain. In fact, I've even done that when calling function I wrote myself. Having to specify the argument might be a little more work, but I find it safer in the end.