Passing parameters by value
Strings, numbers, and booleans are passed to the function by value. In other words, when a value is passed to a function, that function receives a copy of that value. Let’s see what this means in practical terms:
function change(x){ x = 2 * x; console.log("x in change:", x); } varn = 10; console.log("n before change:", n); // n before change: 10 change(n); // x in change: 20 console.log("n after change:", n); // n after change: 10
The change function takes some number and doubles it. When the change function is called, the number n is passed to it. However, after calling the function, we see that the number n has not changed, although the value of the parameter has increased in the function itself. Because when the change function is called, it gets a copy of the value of the variable n. And any changes with this copy do not affect the variable n itself.
Passing by reference
Objects and arrays are passed by reference. That is, the function receives the object or array itself, and not a copy of them.
function change(user){ user.name = "Tom"; } var bob ={ name: "Bob" }; console.log("before change:", bob.name); // Bob change(bob); console.log("after change:", bob.name); // Tom
In this case, the change function takes an object and changes its name property. As a result, we will see that after the function call, the original bob object that was passed to the function has changed.
However, if we try to reset the entire object or array, the original value will not change.
function change(user){ // полная переустановка объекта user= { name:"Tom" }; } var bob ={ name: "Bob" }; console.log("before change:", bob.name); // Bob change(bob); console.log("after change:", bob.name); // Bob
The same goes for arrays:
function change(array){ array[0] = 8; } function changeFull(array){ array = [9, 8, 7]; } var numbers = [1, 2, 3]; console.log("before change:", numbers); // [1, 2, 3] change(numbers); console.log("after change:", numbers); // [8, 2, 3] changeFull(numbers); console.log("after changeFull:", numbers); // [8, 2, 3]