JavaScript call(), apply(), and bind() explained

Day 2/50 – JavaScript Interview Question? Question: What's the difference between call(), apply(), and bind()? Simple Answer: All three methods allow you to set the this context explicitly. call() invokes the function immediately with arguments passed individually, apply() invokes it with arguments as an array, and bind() returns a new function with this bound permanently. 🧠 Why it matters in real projects: These methods are crucial when working with object methods, event handlers, and callbacks where you need precise control over the this context. They're especially important in React class components and when borrowing methods between objects. 💡 One common mistake: Using bind() and expecting the function to execute immediately. Remember, bind() returns a new function—it doesn't invoke it! 📌 Bonus: const person = { name: 'Alice' }; function greet(greeting) { console.log(`${greeting}, ${this.name}`); } greet.call(person, 'Hello'); // "Hello, Alice" greet.apply(person, ['Hi']); // "Hi, Alice" const boundGreet = greet.bind(person); boundGreet('Hey'); // "Hey, Alice" #JavaScript #WebDevelopment #Frontend #LearnInPublic #InterviewQuestions #Programming #TechInterviews

To view or add a comment, sign in

Explore content categories