Function length property is not to be trusted

Robin Pokorny
Jan 19, 2018 · 2 min read

Stefan shows how a function length is computed when it includes a rest parameter or parameters with a default value.

A quick summary:

const fn1 = (a    , b    ) => { }
const fn2 = (a , ...b ) => { }
const fn3 = (a , b = 2) => { }
const fn4 = (a = 1, b ) => { }
fn1.length // -> 2
fn2.length // -> 1
fn3.length // -> 1
fn4.length // -> 0

After a parameter with default

The last one, fn4, is the most interesting case and—as Stefan remarks—good to know.

Actually, I would say it is even more interesting. The interpret generally distinguishes between no default value and default value set to undefined; however, it has no effect on the function execution.

const fn1 = (a            , b            ) => { }
const fn5 = (a = undefined, b = undefined) => { }
fn5.length // -> 0

Surely, fn1 and fn5 behave exactly the same. The only observable difference is the function length.

As per the specs, internally, parameters without default that appear after one with default are ‘considered to be optional with undefined as their default value’.

Isn’t it crazy?

Oh, one more thing, fn4 would throw a syntax error in some older versions of Firefox.

The length can change

This is some surprise. Yet, indeed, the length of a function can change.

const fn1 = (a, b) => { }
fn1.length // -> 2
// some magicfn1.length // -> 3

What could that magic be?

Assigning something to it would be ignored. (Compare to Array.length.)

fn1.length = 3
fn1.length // -> 2

The trick is that the length property of a function has the configurable attribute set to true.

Object.defineProperty(fn1, 'length', { value: 3 })
fn1.length // -> 3

We can go even further and make the property writable:

Object.defineProperty(fn1, 'length', { writable: true })
fn1.length = 0
fn1.length // -> 0

Right. I know. It is weird.

Valid? Totally.

Valid to use? Hopefully not.

See the example in JSBin:

It is worth noting that this is possible since ES2015.

If you like this post, please don’t forget to give a 👏 below. Every clap notification is a motivational boost for me.

If you would like to learn more, I recently started a YouTube channel about JavaScript. I post new video every week, so consider subscribing. Be there from the beginning and help me get better.

Robin Pokorny

Written by

Zealous JavaScript Engineer – Speaks – Explores Elm – Loves maths – Reads specs – Lives in Berlin

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade