Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created July 12, 2023 20:51
Show Gist options
  • Save dfkaye/d563f7a253d4cdb24c7b9e6b0ef65805 to your computer and use it in GitHub Desktop.
Save dfkaye/d563f7a253d4cdb24c7b9e6b0ef65805 to your computer and use it in GitHub Desktop.
call or apply: which do I use? tl;dr, use `f.apply([].concat(args));`
// 11 July 2023
// call or apply: which do I use?
// should I distinguish between a single argument vs. an array of arguments?
// I've seen code like the following too many times used to determine whether to
// use `call()` or `apply()` on a function based on the number of arguments to
// be passed into that function:
/*
```
args.length // if length is defined, args is an array (maybe)
? f.apply(_, args)
: f.call(_, args);
```
*/
// Clarity: Both methods accept a first argument used as the function's scope,
// or `this` context, but differ in the second argument. `call()` accepts one
// value and uses it as first argument (`arguments[0]`) whereas `apply()` takes
// an array of values and populates each item into its corresponding index in
// the `arguments` object.
// Interesting, good to know, one of those dusty corner cases, this distinction
// between `call()` and `apply()`, in this case, is not necessary.
// You can create an array using the `Array.concat()` method, and define it
// inline when calling the function's `apply()` method:
/*
```
f.apply([].concat(args));
```
*/
// *One True Way*. It rarely happens. Celebrate it.
/* test it out */
var a = 1;
var b = ['2', 3];
var c = '4';
function f(a,b,c,d) {
console.log(Array.from(arguments));
}
f.apply(0, [].concat(a));
// Array [ 1 ]
f.apply(0, [].concat(b));
// Array [ "2", 3 ]
f.apply(0, [].concat(a, b));
// Array(3) [ 1, "2", 3 ]
f.apply(0, [].concat(a, b, c));
// Array(4) [ 1, "2", 3, "4" ]
f.apply(0, [].concat(b,c));
// Array(3) [ "2", 3, "4" ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment