Facebook Pixel

Practical Use Cases for call, apply, and bind

Real-world use cases for call, apply, and bind in JavaScript.

Practical Use Cases for call, apply, and bind

1. Borrowing Array Methods

const args = Array.prototype.slice.call(arguments); const nodes = Array.prototype.forEach.call(document.querySelectorAll("*"), fn);

2. Fixing this in Callbacks

setTimeout(obj.greet.bind(obj), 1000); button.addEventListener("click", obj.handleClick.bind(obj));

3. Partial Application

const add = (a, b, c) => a + b + c; const add5 = add.bind(null, 5); add5(3, 2); // 10

4. Finding Max/Min in Array

Math.max.apply(null, [1, 2, 3]); // 3 // or with spread: Math.max(...[1, 2, 3]); // 3

5. Chaining Constructors

function Person(name) { this.name = name; } function Employee(name, id) { Person.call(this, name); // borrow Person constructor this.id = id; }

6. Context in forEach

array.forEach(function(item) { this.doSomething(item); }, context); // or with bind: array.forEach(this.doSomething.bind(this));

The Takeaway

Practical use cases: borrowing array methods (slice.call), fixing this in callbacks (bind), partial application (bind with preset args), Math.max/min with arrays (apply), chaining constructors (call), and context in forEach (second argument or bind).

Use call: Array.prototype.slice.call(arguments) borrows slice to convert array-like objects to arrays. Array.prototype.forEach.call(nodeList, fn) borrows forEach for NodeLists.

Use bind: setTimeout(obj.method.bind(obj), 1000). Or use an arrow wrapper: setTimeout(() => obj.method(), 1000). bind permanently sets this for the returned function.

Math.max.apply(null, [1, 2, 3]) returns 3. In modern JS, use spread: Math.max(...[1, 2, 3]). Both work, but spread is more readable.

In the child constructor, call the parent constructor with this: Person.call(this, name). This borrows the parent constructor and sets properties on the child instance.

const add5 = add.bind(null, 5) creates a function where the first argument is always 5. When called with (3, 2), it calls add(5, 3, 2). This is partial application.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.