6

Why do exported arrow functions NOT retain their name and is there a way to have them do so?

Give an ES6 Module like below:

myModule.js

export function doSomeWork1() {
}
export const doSomeWork2 = () => {
};

If I then import them into another file like so the exported function retains its name while the arrow function does not.

example.js

import { doSomeWork1, doSomeWork2 } from './myModule';
console.log('doSomeWork1...');
console.log(doSomeWork1);
console.log(doSomeWork1.name); // name is retained    
console.log('doSomeWork2...');
console.log(doSomeWork2);
console.log(doSomeWork2.name); // name is NOT retained

output:

doSomeWork1...
[Function: doSomeWork1]
doSomeWork1
doSomeWork2...
[Function]

If I were to declare an arrow function in an ES6 Module without exporting it and print it out directly in that file it does retain it's name.

myModule.js

const doSomeWork3 = () => {
};
console.log('doSomeWork3...');
console.log(doSomeWork3);
console.log(doSomeWork3.name); // name is retained 

output:

doSomeWork3...
[Function: doSomeWork3]
doSomeWork3
TugboatCaptain
  • 4,150
  • 3
  • 47
  • 79
  • 1
    This might be a bug in the engine (or behavior not yet supported). [`export const`](http://www.ecma-international.org/ecma-262/7.0/#prod-ExportDeclaration) should use the same behavior as `const` on its own, which [is defined to give names to anonymous functions](http://www.ecma-international.org/ecma-262/7.0/#sec-let-and-const-declarations-runtime-semantics-evaluation) (see step 5 under *`LexicalBinding : BindingIdentifier Initializer`*). – Jonathan Lonowski May 20 '17 at 23:39
  • Jonathan is right. `console.log(doSomeWork3.name)` works in Chromium, but not in Firefox (where you get an empty string). – Badacadabra May 20 '17 at 23:51
  • This is in Node 6.9.2 (server-side). I am using babel.js to transpile from ES6 modules to common.js format using the 'babel-plugin-transform-es2015-modules-commonjs' package. Maybe its the culprit? – TugboatCaptain May 21 '17 at 00:03
  • Babel has no way to do this unless you also convert the arrow functions to function expressions. – loganfsmyth May 21 '17 at 03:03
  • The warning on [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name), in the _JavaScript compressors and minifiers_ section might be of help here. – maazadeeb May 21 '17 at 03:04
  • Pretty much all covered here I think: [How do I write a named arrow function in ES2015?](http://stackoverflow.com/questions/27977525/how-do-i-write-a-named-arrow-function-in-es2015) – jfriend00 May 21 '17 at 06:48

1 Answers1

1

I just tried that and also export let func123 = () => {} and it worked for "const" and for "let" too. maybe is some configuration that you are using? are you using webpack or something?

UXDart
  • 2,500
  • 14
  • 12