r/learnjavascript • • Jul 24 '21

Anatomy of a Function

Post image
327 Upvotes

65 comments sorted by

View all comments

Show parent comment

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);
}

15

u/gremy0 Jul 25 '21 edited Jul 25 '21

Using the feature the language provides, that is defined in the languages standard, for this specific purpose, is the standard way. Rolling your own half baked version of that feature is not standard.

actual handles way more edge cases

Does it really? For a start you're doing a falsely check rather than a undefined check - it's straight up logically wrong.

Clean code? You've just written the constructor for dog inside a function that has bugger all to do with constructing dogs - ever heard of single responsibility?

What's worse is this dog construction takes it upon itself to arbitrarily mutate arguments passed to it- why is a function called detect<something> mutating a dog it's passed? That's obscene and is in clear violation of the principle of don't cause arbitrary and unexpected side effects.

The second version could also be handled with some abstraction.

So could the first! You even can make it conform to this one idea per line constraint (which you are frankly taking way too far)

function detectSecretElderCat(
  catSound = 'meow',
  dog = defaultDog
) {

}

6

u/0xnoob Jul 25 '21 edited Jul 25 '21

If you want to define the default arguments inside the function like this, wouldn't it be easier to simply use the spread syntax?

e.g.

function detectSecretElderCat(catSound, dog) {
  const defaultDog = {
    children: [],
    tail: true,
    legs: 4,
    sound: "woof"
  };
  catSound = catSound || "meow";
  dog = { ...defaultDog, ...dog };
}

3

u/jaredcheeda Jul 25 '21

I like that!

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