JS Clean Code tip: Don't use tuples for returned objects

András Tóth - Jan 6 '21 - - Dev Community

I am not going to talk about the Record & Tuple Proposal, but about this bad habit:

function createSomething() {
  const thing1 = { 
    aProperty: 'indeed'
  };

  function thing2() { /* ... */ }

  return [thing1, thing2];
}
Enter fullscreen mode Exit fullscreen mode

There is absolutely everything wrong with this example. Honestly I was kinda surprised to see it in actual production code.

The problem is losing naming

So let's see some examples of using the thing above:

// Having a typo won't cause any errors
// but you won't find the usages.
const [thang, thing2] = createSomething();

// This is not just valid, but super misleading!
// You accidentally changed the order and you had no errors!
const [thing2, thing1] = createSomething();
Enter fullscreen mode Exit fullscreen mode

We are losing the meaningful names still intact inside createSomething with nothing in return. (React team uses this actually to name your hooks in any way you want - but they also try to enforce naming through linter rules).

How to fix it

Simply return an object:

return { thing1, thing2 };
Enter fullscreen mode Exit fullscreen mode

And this is how you use it:

// will cause error
const { thang, thing2 } = createSomething();

// order does not matter, no penalty 
// if you misremember the order
const { thing2, thing1 } = createSomething();
Enter fullscreen mode Exit fullscreen mode

💪 🦾 💪 🦾 💪 🦾 💪 🦾

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .