JavaScript Corners – Part 5
Here’s a quick one:
let f = function() {}; console.log(f.name); // prints f
This was quite unexpected to me. It’s the only time I’ve ever seen where the left-hand side of an assignment can affect the right-hand side.
This only happens once. Once the anonymous function has a name, it can’t be re-named:
let f = function() {}; let g = f; console.log(g.name); // prints f
Interestingly, this doesn’t seem to work with destructuring:
let [f] = [function(){}]; console.log(f.name); // prints ''
This implies that somewhere between when the anonymous function is instantiated, and when it added to the array literal, the anonymous function acquires a name. It’s not the destructuring itself that suppresses the name, as can be seen in the following example:
let [f = function(){}] = []; console.log(f); // prints f
It also doesn’t seem to work with anonymous functions passed as parameters:
(function(f) { console.log(f.name); })(function() {});
It also doesn’t seem to work with anonymous functions evaluated from more complicated expressions:
let foo = (42, function() {}); console.log(foo.name); // prints ''