What are the differences between JavaScript's bind(), call(), and apply()?
Richard W
richard w profile pic

1. Checking if an Element is the Last Child of its Parent: - To check if an element is the last child of its parent in JavaScript, you can use theNode.parentNode property to access the parent node and then compare the element with the last child of the parent node. - If the element matches the last child, it is considered the last child of its parent.

1
2
3
4
5
6
7

   function isLastChild(element) {
     const parent = element.parentNode;
     const lastChild = parent.lastChild;
     return element === lastChild;
   }
   

In this example, theisLastChild() function takes an element as an argument and returnstrue if it is the last child of its parent, andfalse otherwise. 2. Differences betweenbind(),call(), andapply(): -bind(): Thebind() method creates a new function that, when called, has itsthis value set to a specified object. It returns a new function that you can invoke later. - Usage:function.bind(thisArg, arg1, arg2, ...) -call(): Thecall() method calls a function with a giventhis value and arguments provided individually. It immediately invokes the function. - Usage:function.call(thisArg, arg1, arg2, ...) -apply(): Theapply() method calls a function with a giventhis value and arguments provided as an array (or an array-like object). It immediately invokes the function. - Usage:function.apply(thisArg, [argsArray]) The main differences between these methods are in how they handle arguments and when the function is invoked: -bind() returns a new function with the boundthis value and any specified arguments. It doesn't immediately execute the function. -call() andapply() immediately invoke the function with the specifiedthis value and arguments. -call() expects arguments to be passed individually, whileapply() expects arguments as an array or array-like object. Here's an example illustrating the differences:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

   const person = {
     name: 'John',
     greet: function (message) {
       console.log(`${message}, ${this.name}!`);
     },
   };

   const boundGreet = person.greet.bind(person);
   boundGreet('Hello'); // Output: "Hello, John!"

   person.greet.call(person, 'Hi'); // Output: "Hi, John!"

   person.greet.apply(person, ['Hey']); // Output: "Hey, John!"
   

In this example,bind() creates a new functionboundGreet that is bound to theperson object. WhenboundGreet is invoked, it still retains theperson object as itsthis value. call() andapply() immediately invoke thegreet function with theperson object as thethis value and the provided argument(s). Choose the appropriate method based on your use case.bind() is useful for creating new functions with preset arguments andthis values.call() andapply() are suitable for immediate function invocation with the specifiedthis value and arguments.