1

It is said in w3cschool that "If a function changes an argument's value, it does not change the parameter's original value."

However, i don't quite understand that with the following example:

function bar(a){
    arguments[0] = 10;
    console.log("a",a);//10
    return a;
}
function foo(cc){
    cc = 10;
    return arguments[0];
}
console.log(bar(333));//10
console.log(foo(333));//10

I have tested them in both chrome and firefox. From my understanding , if argument value changes can not lead to parameter value change, why 'bar' fail to return 333?

Hank
  • 331
  • 1
  • 13
  • 1
    We'd really need to see the context of that statement (though W3Schools is normally considered a poor reference site) but the thumb rule is: scalars are passed by value, objects are passes by reference. Whatever, you aren't really testing whether the original variable changes—you don't even have an original *variable*. – Álvaro González Nov 18 '15 at 09:03
  • 1
    argument inside function does change, but original argument is not `var x = 333; bar(x); console.log(x); // 333` – EekTheCat Nov 18 '15 at 09:03
  • Also see answers to : http://stackoverflow.com/q/518000/1531054 – S.D. Nov 18 '15 at 09:14
  • please read this http://www.w3schools.com/js/js_function_parameters.asp .. JavaScript functions have a built-in object called the arguments object. The argument object contains an array of the arguments used when the function was called (invoked). – Adarsh Mohan Nov 18 '15 at 09:16

2 Answers2

3

Given a function:

function bar(a) {
  arguments[0] = 10;
  return a;
}

Calling it like bar(50) will return 10, because the value inside bar's scope was replaced by 10.

What "If a function changes an argument's value, it does not change the parameter's original value." means is that doing:

var x = 90;
var y = bar(x);

console.log(y);
console.log(x);
// y is 10
// x is still 90 

... won't change the value of x outside of bar.


For more info see:

2

As Rudolfs stated the rule is related to the variable in the outer scope. But it is not always true. For arrays & objects the rule is not applied

function modify(obj) {
  obj.value = 'modified';
}

var objOuter = {value: 'original'};

console.log('The original value is ' + objOuter.value); //original
modify(objOuter);
console.log('The modified value is ' + objOuter.value); //modified
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50