javascriptarguments

Why does modifying function parameters modify the `arguments` object as well?


Observe:

function myFunc(arg1, arg2) {
  if (arguments.length < 2) { // Only one argument received
    arg1 = "Default"; // Set arg1 to some default value
    arg2 = arguments[0]; // Use the first argument passed for arg2
  }
  return [arg1, arg2];
}

myFunc("Hello", "World"); //=> ["Hello", "World"]

// So far, so good. Now let's try one that uses the default value for arg1:

myFunc("World"); //=> ["Default", "Default"]

What the heck, JavaScript? What's going on here? Why does JavaScript behave this way?


Solution

  • You are overwriting your first argument before using its value:

    arg1 = "Default"; // Set arg1 to some default value
    arg2 = arguments[0]; // Use the first argument passed for arg2
    

    So the value of arg2 is set to the value "Default" rather than the original value.