0

Please, could you help me to figure out my problem. I'm trying to return changed object via function parameter but it does not work for me as I expect. I'm using Node.js version 13.8.0 under Windows 10 Professional Edition.

Below is a code snippet that I'm struggling with:

function a(x)
{
    var r = { v1: 0.0, v2: 0.0};
    r.v1 = 2.0 * x;
    r.v2 = x * x;
    return r;
}

function b(x, r)
{
    r = a(x);
}

var rr = { v1: 100.0, v2: 1000.0 };
b(5.0, rr);

console.log(rr);

At the end I expect that console.log(rr) will print out "{ v1: 10.0, v2: 25.0 }" but instead I have the "{ v1: 100.0, v2: 1000.0 }".

ESLint shows one error that does not seems to me important. 1 What I'm doing wrong?

Lieh Tzu
  • 3
  • 1
  • Does this answer your question? [JavaScript by reference vs. by value](https://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value) – theBittor Apr 18 '20 at 12:07

1 Answers1

0

Here is the solution for your issue.

function a(x)
{
    var r = { v1: 0.0, v2: 0.0};
    r.v1 = 2.0 * x;
    r.v2 = x * x;
    return r;
}

function b(x, r)
{
    let changedObj = a(x);
    r.v1 = changedObj.v1;
    r.v2 = changedObj.v2;
    
}

var rr = { v1: 100.0, v2: 1000.0 };
b(5.0, rr);

console.log(rr);
Sifat Haque
  • 5,357
  • 1
  • 16
  • 23
  • That's not that I'm looking for. I understand that I can *return* updated object but I NEED TO RETURN IT VIA FUNCTION PARAMETER. (Just in case if there will be two, three or more objects to return.) – Lieh Tzu Apr 18 '20 at 12:14
  • @LiehTzu Would you please check now? – Sifat Haque Apr 18 '20 at 12:31