Skip to content

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 length for (a, b), (a, b = 1, c), (...all) and ({ a, b })?
  • Where does an anonymous function's name come from, and what name do a bound function, a getter and a class get?
  • What happens when you assign to fn.name in a module, and how does Object.defineProperty change 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

Sources to start from