Get a function's name in JavaScript
Intermediate · 4 min read
Every JavaScript function carries a name property. You rarely set it yourself, but you see it all the time: in error messages, in stack traces when something crashes, and in the browser's developer tools. Knowing where that name comes from helps you read those messages, and tells you when a function will show up as nameless.
In this tutorial you will write nameOf(fn), a small function that reads a function's name, and then try it on every common way of making a function. Some of the results are surprising. You need to know what a function is and how arrow functions look.
The name property
For a plain function declaration, name is simply the name you wrote:
function greet() {}
console.log(greet.name); // 'greet'
For other kinds of functions, JavaScript often infers the name, meaning it works it out from the code around the function. Most of this lesson is about those cases.
Checking the type first
Only functions have a meaningful name. Reading .name from a number gives undefined, which hides the mistake. typeof tells you what kind of value you have:
console.log(typeof greet); // 'function'
console.log(typeof 42); // 'number'
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
29 Get a function’s name
fairRead the name of a function. Then find the cases where the name is empty or not what you expected.
Stuck? Three hints, smallest first
- 1.
fn.nameis the property. It is read-only in practice. - 2. An arrow function assigned to a variable takes the variable’s name.
- 3. A truly anonymous function passed directly as an argument has an empty name.
Step 1: a safe nameOf
Refuse anything that isn't a function, then return its name:
const nameOf = (fn) => {
if (typeof fn !== 'function') throw new TypeError('not a function');
return fn.name;
};
console.log(nameOf(greet)); // 'greet'
try { nameOf(42); } catch (e) { console.log(e.name); } // 'TypeError'
A TypeError is the built-in error for "this value is the wrong kind of thing".
Step 2: names taken from the variable
An arrow function has no name of its own. When you assign it to a variable, JavaScript gives it the variable's name. The same happens to an unnamed function expression:
const arrow = () => {};
const assignedAnon = function () {};
console.log(nameOf(arrow)); // 'arrow'
console.log(nameOf(assignedAnon)); // 'assignedAnon'
The name is set once, when the function is created. Assigning the same function to another variable later doesn't rename it.
Step 3: a named function expression keeps its own name
If the function expression has a name of its own, that name wins over the variable:
const named = function theRealName() {};
console.log(nameOf(named)); // 'theRealName'
That surprises people who expect 'named'.
Step 4: methods and classes
A shorthand method in an object takes its key as its name. A class is a function under the hood, so it has a name too, and so do its methods:
const { method } = { method() {} };
class Bus { static go() {} board() {} }
console.log(nameOf(method)); // 'method'
console.log(nameOf(Bus)); // 'Bus'
console.log(typeof Bus); // 'function'
console.log(nameOf(Bus.go)); // 'go'
console.log(nameOf(Bus.prototype.board)); // 'board'
const { method } = ... pulls the method property out of the object into its own variable. static go belongs to the class itself, while board lives on Bus.prototype, the shared object every bus made with new Bus() uses.
Step 5: bind adds a prefix
bind makes a new function tied to a chosen this, the object a function works on when it runs. Its name gets the word bound in front:
function declared() {}
const bound = declared.bind(null);
console.log(nameOf(bound)); // 'bound declared'
If you see bound in a stack trace, this is where it came from.
Step 6: the nameless case
A function written straight into a call, with no name, has nothing to take a name from:
let nameOfLiteral = null;
(function (fn) { nameOfLiteral = fn.name; })(function () {});
console.log(nameOfLiteral === ''); // true: the name is an empty string
The outer function receives the inner one as fn and reads its name. It is empty, because the inner function was never assigned to anything. This is exactly the case where you most want a name: a callback that crashes shows up in the stack trace as anonymous. Giving your callbacks names, like function onSave() {}, makes errors easier to trace.
Step 7: the name is read-only
Assigning to name doesn't change it. Outside strict mode the assignment is silently ignored; in strict mode it throws a TypeError. To rename a function on purpose, use Object.defineProperty:
const f = () => {};
try { f.name = 'other'; } catch {}
console.log(f.name); // 'f'
Object.defineProperty(f, 'name', { value: 'renamed' });
console.log(f.name); // 'renamed'
Built-in functions have names too: Math.max.name is 'max'.
Step 8: a cousin, length
Functions also have a length: the number of parameters before the first one with a default value or a rest parameter.
console.log(((a, b) => a + b).length); // 2
console.log(((a, ...rest) => a).length); // 1
console.log(((a, b = 1, c) => a).length); // 1
Neither name nor length is reliable enough to build program logic on. They are there to help you read what is going on.
The full solution
The panel has nameOf and every kind of function from this lesson. It prints a table of each one next to its name, ending with the empty name of the function passed straight into a call. Press Run to see the output.
const nameOf = (fn) => {
if (typeof fn !== 'function') throw new TypeError('not a function');
return fn.name;
};
function declared() {}
const arrow = () => {};
const assignedAnon = function () {};
const named = function theRealName() {};
const { method } = { method() {} };
class Bus { static go() {} board() {} }
const bound = declared.bind(null);
// The name is inferred from the assignment, so passing a function literal
// straight into a call gives it nothing to infer from.
let nameOfLiteral = null;
(function (fn) { nameOfLiteral = fn.name; })(function () {});
const rows = [
['function declared() {}', nameOf(declared)],
['const arrow = () => {}', nameOf(arrow)],
['const assignedAnon = function () {}', nameOf(assignedAnon)],
['const named = function theRealName() {}', nameOf(named)],
['{ method() {} }', nameOf(method)],
['class Bus', nameOf(Bus)],
['Bus.go (static)', nameOf(Bus.go)],
['Bus.prototype.board', nameOf(Bus.prototype.board)],
['declared.bind(null)', nameOf(bound)],
['a literal passed as an argument', nameOfLiteral],
];
for (const [what, name] of rows) console.log(what.padEnd(40), JSON.stringify(name));
Output
20 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 20 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a declared function knows its name', nameOf(declared), 'declared');
test('an arrow takes the variable name', nameOf(arrow), 'arrow');
test('so does an anonymous function expression', nameOf(assignedAnon), 'assignedAnon');
test('a named function expression keeps its own name', nameOf(named), 'theRealName');
test('not the variable it was assigned to', nameOf(named) === 'named', false);
test('a shorthand method takes the key', nameOf(method), 'method');
test('a class is a function with a name', nameOf(Bus), 'Bus');
test('and typeof confirms it', typeof Bus, 'function');
test('a static method is named', nameOf(Bus.go), 'go');
test('and a prototype method', nameOf(Bus.prototype.board), 'board');
test('binding prefixes the name', nameOf(bound), 'bound declared');
test('a literal passed straight as an argument has NO name', nameOfLiteral, '');
test('because there was nothing to infer it from', nameOfLiteral.length, 0);
test('a non-function is refused', (() => { try { nameOf(42); return 'no error'; } catch (e) { return e.constructor.name; } })(), 'TypeError');
test('the name is not writable by assignment', (() => { const f = () => {}; try { f.name = 'other'; } catch {} return f.name; })(), 'f');
test('but it can be redefined deliberately', (() => { const f = () => {}; Object.defineProperty(f, 'name', { value: 'renamed' }); return f.name; })(), 'renamed');
test('a built-in reports its own name', Math.max.name, 'max');
test('and length is the declared parameter count', ((a, b) => a + b).length, 2);
test('which ignores a rest parameter', ((a, ...rest) => a).length, 1);
test('and stops at the first default', ((a, b = 1, c) => a).length, 1);
fn.name is mostly inferred rather than intrinsic. An arrow function has no name of its own, so the engine takes it from the variable it is assigned to — which is why arrow.name is 'arrow'. Assign the same function elsewhere and the name does not follow.
Two results are worth remembering. A named function expression keeps its own name, not the variable's, so const named = function theRealName() {} reports 'theRealName'. And a function literal passed directly as an argument has an empty name, because there is no assignment to infer from — which is exactly the case where you most want a name, in a stack trace. That is a real argument for naming your callbacks.
bind prefixes 'bound ', so a bound function's name is 'bound declared'. And the assertions on length are a related surprise: it counts parameters before the first default or rest parameter, so (a, b = 1, c) => … reports 1. Neither name nor length is reliable enough to build logic on; both are for diagnostics.
Common mistakes
- Expecting a named function expression to take the variable's name.
const named = function theRealName() {}reports'theRealName'. - Relying on the name of an inline callback. A function written straight into a call has an empty name. Name it if you want readable stack traces.
- Trying to rename a function by assignment.
f.name = 'x'does nothing. UseObject.definePropertywhen you really need to.
Try it yourself
- Assign
arrowto a new variable,const copy = arrow, and check thatcopy.nameis still'arrow'. - Find the name of
[].map. You should get'map'. - Write
describe(fn)that returns text like'add takes 2 arguments', usingnameandlength.