Function length property is not to be trusted

Robin Pokorny
2 min readJan 19, 2018

--

This article is a reply to stefan judis's article How the rest operator and default values affect the function length property.

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
Robin Pokorny

Written by Robin Pokorny

Architecture & Tech Leadership — Speaks — Loves maths — Reads specs — Podcasts — Lives in Berlin — robinpokorny.com

Responses (1)