4. What is apply function?

apply invoked on a function allows to pass an object, which will be used as this. It loads context of the function

apply is different from bind - in apply function is invoked immediately with parameters passed as a second argument of apply. This second argument is an array of parametres, which will be passed to function in the same order.

const person = { firstName: "Mario", print: function (arg1, arg2) { console.log( `I'm ${this?.firstName} and this is an arg1: ${arg1} and arg2: ${arg2}` ); }, }; person.print(); // I'm Mario and this is an arg1: undefined and arg2: undefined const printFunction = person.print; printFunction(); // I'm undefined and this is an arg1: undefined and arg2: undefined printFunction.apply(person); // I'm Mario and this is an arg1: undefined and arg2: undefined printFunction.apply(person, ["arg1", "arg2"]); // I'm Mario and this is an arg1: arg1 and arg2: arg2

apply is different from call - in apply arguments passed to function are taken from array passed as second argument, while in call they are speparated with comma.

printFunction.apply(person, ["arg1", "arg2"]); // I'm Mario and this is an arg1: arg1 and arg2: arg2 printFunction.call(person, "arg1", "arg2"); // I'm Mario and this is an arg1: arg1 and arg2: arg2
Struggling to find common date to meet with your friends? Try our new tool commondate.xyz
devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.

Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz