Functions are objects — properties, length, name, and passing them around¶
Level: 101 · for anyone who has passed a function as an argument
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: A function is an object: it takes new properties, and its own length stops counting at the first default parameter — (a, b = 1, c) => {} has length 1 — while name is inferred from the variable an anonymous function is assigned to.
Keywords: fn.length, fn.name
What the finished page will answer¶
- What is
lengthfor(a, b),(a, b = 1, c),(...all)and({ a, b })? - Where does an anonymous function's
namecome from, and whatnamedo a bound function, a getter and a class get? - What happens when you assign to
fn.namein a module, and how doesObject.definePropertychange it anyway? - Can a function keep a call count in a property of itself, and how does that compare with keeping it in a closure?
Examples it will need¶
-
functions_are_objects_length_name_js.js— length and name for a dozen function shapes: plain, defaults, rest, destructured, anonymous, arrow, method, getter, bound, class -
functions_are_objects_readonly_name_js.js— an assignment to fn.name that throws a TypeError in a module, then the same rename done with Object.defineProperty -
functions_are_objects_expando_ts.ts— a call counter stored as a property of its own function, which tsc accepts as an expando declaration, and the count after two calls
See also¶
- Higher-order functions — passing a function to another function as a value
- Parameters — the defaults and rest parameters length stops at
typeof— why typeof says function for this one kind of object- Property descriptors — why name and length refuse a plain assignment
- Rust: Function pointers ↗ — how Rust holds a function: eight bytes of code address, no properties