whatstheoutput_

#76: sum.call vs sum.apply

Topic: this · Difficulty: ★

function sum(a, b) { return a + b; }
console.log(sum.call(null, 1, 2));
console.log(sum.apply(null, [3, 4]));

Output

3
7

Why

call and apply both invoke a function immediately with a chosen this value (here, null, which sum ignores since it never uses this) — they differ only in how the remaining arguments are supplied. call takes them as a plain comma-separated argument list, so sum.call(null, 1, 2) passes a=1, b=2, giving 3. apply takes them bundled into a single array, so sum.apply(null, [3, 4]) unpacks that array into a=3, b=4, giving 7. Same underlying mechanism (explicit this-binding at call time), just a different calling convention for the arguments.

More this puzzles

Play today's puzzle →