mediumJS ES5#54

Call and apply

Prompt

Write a function sumAll that accepts any number of arguments and returns their sum. Use a loop over the arguments object (not rest params). Zero arguments must return 0.

Solution

function sumAll() {
  var total = 0
  for (var i = 0; i < arguments.length; i++) {
    total += arguments[i]
  }
  return total
}
Mentor's take

Before rest parameters, arguments was the only way to write variadic functions, and it still appears in every ES5 codebase you'll maintain — so interviewers use it to check you know its sharp edges, not because they want you writing it today.

The mechanics: every regular (non-arrow) function gets an arguments binding in its execution context — an array-like object with indexed slots and a length, but not an Array. It has none of the array methods; arguments.map(...) throws. The ES5 conversion idiom is Array.prototype.slice.call(arguments), which works because slice only needs indices and a length from its this. Starting the accumulator at 0 makes the zero-argument case fall out of the loop naturally — no special-casing.

The senior details worth volunteering: arrow functions have no arguments of their own — they see the enclosing function's, same lexical rule as their this. And in sloppy mode, arguments is live-linked to the named parameters (mutating one mutates the other), a misfeature strict mode severs. Today you'd write function sumAll(...nums) and get a real array; knowing both marks you as someone who can read old code and write new code.

Red flag: calling arguments.reduce(...) or arguments.forEach(...) directly. It signals you've never actually run this code — array-like is not array.

Say it: "arguments is array-like, not an array — I loop by index or borrow Array.prototype.slice, and I know arrows don't get their own, which is the same lexical rule as their this."