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 code base.
The lodash _.once method works by returning a function that will call the given function only once when called. Any additionally calls to the function will result in nothing happening.
So the lodash once method can come in handy when I want to log something to the console just once and only once inside a loop of some kind. That being said the lodash once method can come in handy as a kind of debugging tool.
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 same way as if I was to take the time t write them myself.