Answers for "pass by value and pass by reference in javascript"

2

pass by value and pass by reference in javascript

* Pass By Value:

->In Pass by value, parameters passed as an arguments create its own copy.
So any changes made inside the function is made to the copied value not to 
the original value .
 
let a=5;
b=a;
b=a+5;
console.log(a) //output: 5
console.log(b) //output: 10

* Pass By Reference :
->  In JavaScript array and Object follows pass by reference property.
->  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. 

const obj1 = {name:"abc",age:23};
const obj2 = obj1;
obj2.name="xyz";

console.log(obj2.name) //output: xyz
console.log(obj1.name) //output: xyz
Posted by: Guest on September-15-2021
3

javascript pass by reference

function add(a, b, output) {
  output.out = a + b;
}

var output = {};
add(5, 3, output);
console.log(output); //output: {out: 8}
Posted by: Guest on May-20-2020
0

javascript pass by value

function func(obj) {
  obj = JSON.parse(JSON.stringify(obj)); //If too slow, replace with other method of deep cloning
  obj.a += 10;
  return obj.a;
}

var myObj = {a: 5};
func(myObj); //Returns 15 and myObj.a is still 5
Posted by: Guest on May-20-2020

Code answers related to "pass by value and pass by reference in javascript"

Code answers related to "Javascript"

Browse Popular Code Answers by Language