DEV Community

Discussion on: Avoid use IF on our JS scripts

Collapse
mbuechmann profile image
Malte Büchmann

Very nice article. But I think I found one catch:

The rewrite in the second example for ternary operators makes the code very unreadable. The cumbersome part of this example are the else statements. If you use guard clauses if statements, the code becomes much more readable and concise:

function customerValidation(customer) {
  if (!customer.email) {
    return error('email is require');
  } 
  if (!customer.login) {
    return error('login is required');
  }
  if (!customer.name) {
    return error('name is required');
  }
  return customer;
}
Enter fullscreen mode Exit fullscreen mode

In this case, you can even remove the curly braces:

function customerValidation(customer) {
  if (!customer.email)
    return error('email is require');  
  if (!customer.login)
    return error('login is required');
  if (!customer.name)
    return error('name is required');

  return customer;
}
Enter fullscreen mode Exit fullscreen mode

Now both versions are much more readable and the reader can understand the intent of the written code much better: catch errors and return them.

Collapse
damxipo profile image
Damian Cipolat Author

thanks for comment!