Published at
Updated at
Reading time
1min
This post is part of my Today I learned series in which I share all my web development learnings.

Here's Alex MacArthur with a nice JavaScript fun fact: when using JavaScript default parameters, earlier parameters are available to later default parameters.

Let's look at some code from his post because the previous sentence is a mouthful.

// reuse `arg1` and set it as `arg2`
function myFunc(arg1, arg2 = arg1) {
  console.log(arg1, arg2);
}

myFunc("arg1!"); // "arg1!" "arg1!"

That's pretty cool, but when would I use this?

Alex describes using this behavior to make a JavaScript class more testable. Fair, but I rarely use classes paired with dependency injection, so this example isn't convincing for me.

He also came up with the least readable reduce function at all times.

const numbers = [1, 2, 3];

// don't do this ๐Ÿ˜…
const total = numbers.reduce(
  (acc, value, _index, _array, result = acc + value) => result
);

But the post's comments include some gems.

// Make an image a square if not defined otherwise 
// Kudos to Colum
function Image(width, height = width) {}

// Find a string with defined boundaries
// if no boundaries are defined, search the entire string
// Kudos to Axel Rauschmayer
function findIn(str, start = 0, end = str.length) {}

Great examples! I'm convinced and will put reusable function parameters into my JavaScript toolbelt.

If you enjoyed this article...

Join 5.4k readers and learn something new every week with Web Weekly.

Web Weekly โ€” Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles