What is the benefit to name a default export?

Viewed 109

I was looking at this code in an article about imports and exports

export default class User {
  constructor(name) {
    this.name = name;
  }
}

What is the benefit of giving it the name User if the name when it is imported is actually what will be used? I don't see any reason for doing it this way, can someone share one please.

1 Answers

Giving it a name has at least 2 benefits:

  • It can make working with instances (or the constructor) easier when it has a name that can be seen and referred to. In contrast, for example, if you just saw <anonymous>, that isn't a very useful label.
  • If you don't give the class a name when exporting, other users of the class across the codebase may not have any direct guidelines on what name to give the imported class. Naming variables is often considered a significant issue in programming - giving the class a name when exporting can make things easier later.

These are maintainability benefits. Giving the class a name usually won't affect the logic being carried out in any meaningful way, though. The .name will be visible on the class with a name, but it's rarely used:

const obj = {};
obj.containsClass = class {};
console.log(obj.containsClass.name);

obj.containsClass2 = class classTwo {};
console.log(obj.containsClass2.name);

Related