16

I wonder how memory is managed in V8. Take a look at this example:

function requestHandler(req, res){
  functionCall(req, res);
  secondFunctionCall(req, res);
  thirdFunctionCall(req, res);
  fourthFunctionCall(req, res);
};

var http = require('http');
var server = http.createServer(requestHandler).listen(3000);

The req and res variables are passed in every function call, my question is:

  1. Does V8 pass this by reference or does it make a copy in memory?
  2. Is it possible to pass variables by reference, look at this example.

    var args = { hello: 'world' };
    
    function myFunction(args){
      args.newHello = 'another world';
    }
    
    myFunction(args);
    console.log(args);
    

    The last line, console.log(args); would print:

    "{ hello: 'world', newWorld: 'another world' }"
    

Thanks for help and answers :)

roschach
  • 8,390
  • 14
  • 74
  • 124
onlineracoon
  • 2,932
  • 5
  • 47
  • 66

1 Answers1

25

That's not what pass by reference means. Pass by reference would mean this:

var args = { hello: 'world' };

function myFunction(args) {
  args = 'hello';
}

myFunction(args);

console.log(args); //"hello"

And the above is not possible.

Variables only contain references to objects, they are not the object themselves. So when you pass a variable that is a reference to an object, that reference will be of course copied. But the object referenced is not copied.


var args = { hello: 'world' };

function myFunction(args){
  args.newHello = 'another world';
}

myFunction(args);
console.log(args); // This would print:
    // "{ hello: 'world', newHello: 'another world' }"

Yes that's possible and you can see it by simple running the code.

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Not sure if this has changed. My code is updateRatings(req.body) .then((response) => updateAvgRating({guide: response, rating: req.body})) I am modifying the req.body within the first function updateRatings, and that change seems to get reflected within the second function updateAvgRating – runios Aug 22 '17 at 09:52
  • 1
    @runios it is because `body` in your example is an object. It is by value for primitves, i.e. string and numbers. E.g. `function foo() {i++;} let i =0; foo(i); console.log(i)` Sorry for kinda minified js ;-) – Do-do-new Aug 02 '19 at 07:23
  • @runios if you want to change the primitive in your function, wrap it in an object, e.g. `function foo(i) {i.val++;} let i ={}; i.val=0; foo(i); console.log(i.val)` And I forgot `i` as argument in my previous comment, should be `foo(i)` – Do-do-new Aug 02 '19 at 07:28