What is the difference between these functions? Why do they return different values?
function prova1(x){ x = 5;}
var num1 = 3;Â
prova1(num1);Â alert(num1);Â //Â num1Â Â>Â 3
...
function prova2(x) {x.valor = 5;}
var num2 = new Object(); num2.valor = 3;
prova2(num2); alert(num2.valor); // num2.valor Â> 5
...
function prova3(x) {x = new Object(); x.valor = 5;}
var num3 = new Object(); num3.valor = 3;
In JavaScript, parameters are passed by value. You may be wondering:
The answer may seem a bit confusing: in JavaScript everything is passed by value, but "this value" is itself a reference. This is known as call by sharing and is implemented in languages ​​like Java and Python.
If you are astute you will have already identified another question:
The answer is simple but interesting: any modification made to the parameters only lasts as long as the life cycle of the function itself is completed, but if the modification is made to the internal data of a parameter (such as an object) , these modifications propagate .
The third case is interesting:
If you run that code you will see that it
num3
still has a value3
for the inputx
. This happens because you have reassigned a value to the parameter, which makes it a new one.In addition, none does anything that affects the initial variable.
Makes x equal to 5, but returns nothing(Does not affect variable num1).
Creates an object that contains the value parameter assigns 5 to the 'value' parameter (does not affect the num2 object).
And the same as 2.
edited
It returns different values ​​because they are not modified in the function, they only create a variable within it (which is invisible to the other code in this case) and the others are not modified.
Declaration of functions correctly.