JS: Function Name Property
Every function has a own string property "name".
// every function have a own property string key "name" // arrow function console.assert( Object.hasOwn((x) => x + 1, "name"), ); // function defined by keyword function console.assert( Object.hasOwn( function ff(x) { return x + 1; }, "name", ), );
Value of function name property
Arrow function
// value of function name property // anon arrow function name is empty string console.assert( (() => []).name === "", ); // arrow function assigned to var. name is the var name. const ff = (x) => x; console.assert(ff.name === "ff");
Function defined by the keyword function
// keyword function function kwf() { return 3; } console.assert(kwf.name === "kwf"); // keyword function as function expression. // if name appears in the function part, that is the name const fexp = function gg() { return 3; }; console.assert(fexp.name === "gg"); // the name is the variable if no name appears in the function part const fff = function () { return 3; }; console.assert(fff.name === "fff");
Name property not writable
// function name property not writable const ff = (x) => x; try { ff.name = "yes"; } catch (xerror) { console.log(xerror); } // TypeError: Cannot assign to read only property 'name' of function '(x) => x'
Class constructor with property key "name"
if you have a class that already have a name field, it is not overwritten.
class Dog { static name = "hoho"; } console.log(Dog.name); // hoho