Always Name Functions in JavaScript

While using anonymous functions might seem convenient, they can create difficulties when trying to identify performance bottlenecks during profiling. This lesson will demonstrate how named functions make it easier to pinpoint and address performance issues, ultimately leading to more efficient and debuggable code. Learning this practice will greatly improve your ability to locate and fix performance issues in complex projects.

Share with a coworker

Social Share Links

Transcript

[00:00] When I open the DevTools and swap over to the Performance tab, hit record, and then click this button, and hit stop, you'll see that this code of clicking and then running this expensive operation is represented in here by this click and by this function call. Now right now function call is marked as anonymous as you can see here as well. And now imagine you have hundreds of anonymous functions in your project, if not more, with hundreds of clicks and events and you're trying to hunt down a performance issue and all you see in the profile is a bunch of anonymous blocks. Now these days naming a function is as simple as selecting the function and in cursor or other tools hit some AI say name this function hit enter command enter to accept. Now you have a named function so if we make sure we're refreshed we start another profile, we click the button, and we stop the profile.

[00:55] You'll now see a nice handle click defined which we can search for easily in our code base. But not just that we can hit Command-F in the profile, type for handle click, and it'll zero in on that handle click and we could jump around to every instance where that's defined, which makes hunting down performance issues a bajillion times easier.