Part of my debugging process involves placing a console.log in my code at some point to log out to the console the status of some value. Often it might be placed in the body of some code that ends up getting called often, and as such it will get logged to the console a whole bunch of times real fast. This is where using something like _.once in lodash can be helpful when working on a project that uses lodash as part of it’s codebase.
_.once works by returning a function that will call the given function only once when called.
If you have some experience with concept of closures, and guessed that is how _.once works then you would be right.
So the _.once method is a good example of how closures come in handy. Once returns a function within a function, and the value of result in the before helper is what gets returned each time _.once is called.
When it comes to whatever is returned with the method that is given to _.once, the same value will be given each time it is called after it has been called once. The method given will never be called again, but the value returned when it was called will be returned each time.
No problem it’s a simple fix.
The _.once method is a great example of closures in action. For me it was also a great experience to look into the source code of lodash to find that many of these methods work very much the sme way as if I was to take the time t write them myself.