SoFunction
Updated on 2025-03-03

A brief discussion on the modifiability of JavaScript function parameters

It is thought about by a written test question, and usually no one will modify the parameter value inside the function. This is only discussed here, and there are three ways to modify it.

1. Directly modify the formal parameters when the function declaration

Copy the codeThe code is as follows:

function f1(a) {
    alert(a);
a = 1;//Modify the formal parameter a
    alert(1 === a);
    alert(1 === arguments[0]);
}
f1(10);

Function f1 defines parameter a. When calling, pass parameter 10, pop up 10 first, modify a to 1, and pop up true twice, a and arguments[0] are both 1.

2. Modify through the arguments object inside the function

Copy the codeThe code is as follows:

function f2(a) {
    alert(a);
arguments[0] = 1;//Modify arguments
    alert(1 === a);
    alert(1 === arguments[0]);

}

The effect is the same as function f1.

3. Local variables declared internally in the function have the same name as formal parameters

Copy the codeThe code is as follows:

function f3(a) {
    alert(a);
var a = 1;//Declare the local variable a and assign it to 1
    alert(1 === a);
    alert(arguments[0]);
}
f3(10);

Function f3 defines the formal parameter a, and the function internally declares that the local variable a is assigned to 1 at the same time, but a here is still the parameter a, which can be proved that it is modified from the last pop-up arguments[0] to 1.

4. If you just declare the local variable a but do not assign the value, the situation will be different again

Copy the codeThe code is as follows:

function f3(a) {
var a;//Only declare, no assignment
    alert(a);
    alert(arguments[0]);
}
f3(10);

At this time, all 10 pops up, not undefined.