DEV Community

Discussion on: 7 Tips for Clean Code in JavaScript You Should Know

Collapse
 
havespacesuit profile image
Eric Sundquist

Sometimes it is easier to use a boolean flag as a function argument, if splitting the function would result in two almost identical functions. But rather than pass in a boolean, I like to give a unioned string option in TypeScript which is descriptive of what the flag means:

function loadSchema(schema: Schema, sync: 'sync' | 'async') {
 // 
} 

// One eterminty later...

loadSchema("...", 'sync')
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kais_blog profile image
Kai

Yeah, nothing is set in stone. If you feel like this is appropriate, go for it. In my opinion it's much better than a boolen flag already. If you are using TypeScript this is a good alternative. However, for JavaScript I won't recommend this, as you could do the following:

loadSchema("", "fast")
Enter fullscreen mode Exit fullscreen mode

At first glance it's not obvious that "fast" is an invalid argument here.