Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 986
Ajedi32 Avatar asked Mar 27 '26 18:03

Ajedi32


1 Answers

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.

like image 102
Joseph Myers Avatar answered Mar 30 '26 09:03

Joseph Myers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!