A colleague and I recently came across code that used the .length property on a function. This got us asking what this value actually referred to, so I decided to look up the fantastic MDN web docs for some info.

What does it do?

I discovered that function.length is similar to arguments.length but it gives you back the number of arguments a function expects, rather than what is actually passed in.

Image for post
Image for post

But wait, there’s a catch

Like almost anything in JavaScript, there is always some quirky behaviour that one needs to be aware of 😓

This number excludes the rest parameters and only includes parameters before the first one with a default value — MDN

It turns out that rest parameters as well as defaulted parameters do not count towards this number. But what is more interesting is that as soon as a parameter is defined to have a default value within a function, the function.length property only returns the count of parameters that appear before that defaulted parameter, i.e. all following parameters do not count towards the expected arguments. So we see the behaviour below 🤯

Image for post
Image for post

Should I use this?

The behaviour outlined above makes it a fairly unpredictable indication of the number of parameters a function can have. The original code this was seen in was implementing a curry function, however as we have seen, the function.length would cause errors if any parameter was to be defaulted. Still an interesting API to know and understand nonetheless 🙂

Written by

Developer at Xero

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store