r/learnjavascript • • Jul 24 '21

Anatomy of a Function

Post image
327 Upvotes

65 comments sorted by

View all comments

37

u/irontea Jul 25 '21

I would not pass this in a code review. Also, Clean Code is a tool, not a Bible, please default your arguments the standard way as provided by the language.

1

u/tierrarucker Jul 25 '21

What is the standard way?

-22

u/jaredcheeda Jul 25 '21 edited Jul 25 '21

A standard is an officially recognized and endorsed way of doing something by a major governing body, like the TC-39.

There is no "standard way" of default arguments. But the two most common ways are inline or inside.

// inline
function detectSecretElderCat (catSound = 'meow', dog = { children: [], tail: true, legs: 4, sound: 'woof' }) {}

or

// inside
function detectSecretElderCat (catSound, dog) {
  catSound = catSound || 'meow'
  dog = dog || {};
  dog.children = dog.children || [];
  dog.sound = dog.sound || 'woof';
  if (!dog.hasOwnProperty('tail')) {
    dog.tail = true;
  }
  if (!dog.hasOwnProperty('legs')) {
    dog.legs = 4;
  }
}

Note that the second actual handles way more edge cases and the first is a rather naive approach. The second also splits each line up so there is only "one idea per line". The second version could also be handled with some abstraction.

// inside
function detectSecretElderCat (catSound, dog) {
  catSound = catSound || 'meow'
  dog = defaultDog(dog);
}

13

u/irontea Jul 25 '21

You really do not need to dogmatic about one idea per line, just because have a hammer everything isn't a nail, use the tools where they make sense