Understanding Callbacks and Inversion of Control in JavaScript

🟨 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗗𝗮𝘆 𝟰𝟵: 𝗜𝗻𝘃𝗲𝗿𝘀𝗶𝗼𝗻 𝗼𝗳 𝗖𝗼𝗻𝘁𝗿𝗼𝗹 (𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺) In JavaScript, we often use callbacks to handle async tasks — API calls, timers, or events. But callbacks introduce a hidden issue called Inversion of Control. 🔹 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗮 𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸? A callback is a function passed to another function and executed later. 𝘴𝘦𝘵𝘛𝘪𝘮𝘦𝘰𝘶𝘵(() => { 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨("𝘑𝘢𝘷𝘢𝘚𝘤𝘳𝘪𝘱𝘵"); }, 1000); 🔹 𝗪𝗵𝗮𝘁 𝗶𝘀 𝗜𝗻𝘃𝗲𝗿𝘀𝗶𝗼𝗻 𝗼𝗳 𝗖𝗼𝗻𝘁𝗿𝗼𝗹? When we pass a callback, we give control of our code to another function. We don’t control: • When it runs • How many times it runs • Whether it runs at all 🔹 𝗘𝘅𝗮𝗺𝗽𝗹𝗲 𝘢𝘱𝘪.𝘤𝘳𝘦𝘢𝘵𝘦𝘖𝘳𝘥𝘦𝘳(𝘤𝘢𝘳𝘵, 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 () { 𝘢𝘱𝘪.𝘱𝘳𝘰𝘤𝘦𝘦𝘥𝘛𝘰𝘗𝘢𝘺𝘮𝘦𝘯𝘵(); }); Here: • proceedToPayment is our code • createOrder decides when it runs • Our callback executes only when the API decides, based on its internal logic or async events. This is Inversion of Control in action. 🔹 𝗪𝗵𝘆 𝗧𝗵𝗶𝘀 𝗜𝘀 𝗮 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 • Unexpected behavior • Harder debugging • Leads to callback hell in large apps 🔹 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻 Promises and async / await keep control in our hands. 🔹 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 Callbacks give control away. Promises bring it back. 💬 GitHub link in the comments for examples #JavaScript #Day49 #100DaysOfCode #Frontend

To view or add a comment, sign in

Explore content categories