Javascript – don’t add redundant anonymous functions

Many times I see code like this:

then when it gets passed to a button element:

this isn’t wrong in the sense that, the code will still run, because under the hood the DOM is still receiving a reference to a function that can be called when the click event fires, but it is more code than we need. Doing it this way means more memory use, because have now created the someOnClickCb anonymous function, and also an additional anonymous function passed to onClick which will invoke someOnClickCb. Redundant extra step!

Let’s try something cleaner:

The behaviour has not changed, but we have achieved this using only a reference to the original someOnClickCb anonymous function.

Some people will find this all really obvious and think, why would you even make a post on this?? but I see it all the time in code reviews, I see it from developers with 1 year experience, and I see it from developers with 20 years of experience. Let’s not give the JS engine extra work.