Nidhi Jagga’s Post

Controlling `this` in JavaScript: Call vs. Apply vs. Bind. 🎮 One of the most common interview questions for mid-level developers is: "𝑊ℎ𝑎𝑡 𝑖𝑠 𝑡ℎ𝑒 𝑑𝑖𝑓𝑓𝑒𝑟𝑒𝑛𝑐𝑒 𝑏𝑒𝑡𝑤𝑒𝑒𝑛 𝐶𝑎𝑙𝑙, 𝐵𝑖𝑛𝑑, 𝑎𝑛𝑑 𝐴𝑝𝑝𝑙𝑦?" They all do the same core job: They allow you to manually set what `this` refers to inside a function. But they do it in slightly different ways. 𝐇𝐞𝐫𝐞 𝐢𝐬 𝐭𝐡𝐞 𝟏𝟎-𝐬𝐞𝐜𝐨𝐧𝐝 𝐛𝐫𝐞𝐚𝐤𝐝𝐨𝐰𝐧: 1️⃣ 𝐂𝐚𝐥𝐥 & 𝐀𝐩𝐩𝐥𝐲 (𝐓𝐡𝐞 𝐈𝐦𝐦𝐞𝐝𝐢𝐚𝐭𝐞 𝐈𝐧𝐯𝐨𝐤𝐞𝐫𝐬) Both of these execute the function 𝑖𝑚𝑚𝑒𝑑𝑖𝑎𝑡𝑒𝑙𝑦. The only difference is how they handle arguments. • 𝐂𝐚𝐥𝐥: Passes arguments individually (comma-separated).  • 𝑀𝑛𝑒𝑚𝑜𝑛𝑖𝑐: 𝐂all = 𝐂ommas. • 𝐀𝐩𝐩𝐥𝐲: Passes arguments as a single Array.  • 𝑀𝑛𝑒𝑚𝑜𝑛𝑖𝑐: 𝐀pply = 𝐀rray. 2️⃣ 𝐁𝐢𝐧𝐝 (𝐓𝐡𝐞 𝐏𝐥𝐚𝐧𝐧𝐞𝐫) • 𝐁𝐢𝐧𝐝: Does NOT execute the function immediately. • Instead, it returns a 𝐧𝐞𝐰 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐜𝐨𝐩𝐲 with the `this` context permanently locked (bound) to the object you specified. You can then call this new function whenever you want later. 𝐖𝐡𝐲 𝐢𝐬 𝐭𝐡𝐢𝐬 𝐮𝐬𝐞𝐟𝐮𝐥? It allows "Method Borrowing." You can use a method from one object (like a helper function) and use it on a completely different object, just by changing the `this` context! Check out the syntax comparison below! 👇 Which one do you use most often? I find `bind` essential for passing methods into React components or event listeners! #JavaScript #WebDevelopment #CodingInterviews #SoftwareEngineering #Frontend #JSConcepts

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories