Implementing once() Utility in JavaScript for Single Execution

🚀 Day 19/100 – Implementing a Simple once() Utility in JavaScript Today I explored how to create a small but useful JavaScript utility: a function that can run only once. This pattern is often used when we want to prevent duplicate execution, such as initializing something only once or preventing multiple button submissions. 🧠 Problem: Create a function once() that ensures another function can only be executed a single time. ✅ Solution: function once(fn) { let called = false; let result; return function (...args) { if (!called) { called = true; result = fn(...args); } return result; }; } function init() { console.log("Initialization runs"); return "Done"; } const initialize = once(init); initialize(); initialize(); initialize(); ✅ Output: Initialization runs Done Done Done The function executes only the first time, and the result is reused afterwards. 💡 Key Learnings: • Closures help preserve internal state • Useful for initialization logic • Prevents duplicate execution • Small utility but very practical in real-world apps Understanding patterns like this improves how we structure safe and predictable JavaScript code. I’m currently open to Frontend Developer opportunities (React / Next.js) and available for immediate joining. 📩 Email: bantykumar13365@gmail.com 📱 Mobile: 7417401815 If you're hiring or know someone who is, I’d love to connect. #OpenToWork #FrontendDeveloper #JavaScript #ReactJS #NextJS #ImmediateJoiner #100DaysOfCode

To view or add a comment, sign in

Explore content categories