Published at
Updated at
Reading time

This post is part of my Today I learned series in which I share all my learnings regarding web development.

In JavaScript you can get the number of arguments a function is expecting by using the length property. This can be useful when you're a library authors (I guess). My friend Jason asked me for specific use cases I'll think of a few and edit this post later.

function add (a, b) {
  return a + b;

console.log(add.length); // 2

A question that I never asked myself is how the length property is affected be the rest operator (function a (a, ...b) { }).

Big shoutout to the Web Tools Weekly newsletter here. Louis Lazaris does not "only" list tools but also explains nitty gritty JavaScript details like exactly this question about the rest operator and the function length property in the first section of the newsletter.

So! How does the rest operator affect fn.length? Let's have a look at the snippet included in the newsletter.

function myFunc1 (a, ...b) { }
function myFunc2 (a, b, c, ...d) { }
function myFunc3 (...d) { }

console.log(myFunc1.length); // 1
console.log(myFunc2.length); // 3
console.log(myFunc3.length); // 0

As you see above the rest operator does not "count" into the function length property. Interesting!

But this actually got me thinking... what about default values then?

function myFunc1 (a = 1, b = 2) { }
function myFunc2 (a = 1, b) { }
function myFunc3 (a, b = 2) { }

console.log(myFunc1.length) // 0
console.log(myFunc2.length) // 0
console.log(myFunc3.length) // 1

More or less the same thing... not being counted (and when the first argument is a default value the length is zero). Good to know!

This learning is nothing world changing but I think it is good to know these tiny details of the language we write every day. 🎉

Edited: My friend Robin wrote the nice follow up "Function length property is not to be trusted" on this article. So you might wanna check that out.

Related Topics

Related Articles