apply vs call

apply() and call() are common methods to invoke a function.


Following is the syntax of these methods, where fn represents a given function:
fn.apply(context, arrayOfArguments);, arg1, arg2, ...);
As you see, apply requires the arguments as an array, whereas call requires the arguments to be listed explicitly.
For example, the following function returns the sum of three numbers.
const sum = (a, b, c) => a + b + c;

sum.apply(null, [1, 2, 3]);     // 6, 1, 2, 3);        // 6


You can use this mnemonic to remember the differences between apply and call:
A is for array
C is for comma
Hit the Subscribe button for the latest news on my tools. No spam. Ever!
© 2020 Nguyen Huu Phuoc. All rights reserved