1* Pass By Value:
2
3->In Pass by value, parameters passed as an arguments create its own copy.
4So any changes made inside the function is made to the copied value not to
5the original value .
6
7let a=5;
8b=a;
9b=a+5;
10console.log(a) //output: 5
11console.log(b) //output: 10
12
13* Pass By Reference :
14-> In JavaScript array and Object follows pass by reference property.
15-> In Pass by reference, parameters passed as an arguments does not create its own copy, it refers to the original value so changes made inside function affect the original value.
16
17const obj1 = {name:"abc",age:23};
18const obj2 = obj1;
19obj2.name="xyz";
20
21console.log(obj2.name) //output: xyz
22console.log(obj1.name) //output: xyz
23
1function add(a, b, output) {
2 output.out = a + b;
3}
4
5var output = {};
6add(5, 3, output);
7console.log(output); //output: {out: 8}
1function func(obj) {
2 obj = JSON.parse(JSON.stringify(obj)); //If too slow, replace with other method of deep cloning
3 obj.a += 10;
4 return obj.a;
5}
6
7var myObj = {a: 5};
8func(myObj); //Returns 15 and myObj.a is still 5
9
10