1

Are node.js APIs effective with parameter reference, or only good with return values?

For example, will myPath get normalized if I do this:

var path = require('path'),
    myPath = "my/path";
    path.normalize(myPath);

Or will it only work this way:

    myPath = path.normalize("my/path");

I'm just curious.

EDIT: Fantastic and concise explanation here: https://stackoverflow.com/a/3638034/1049693

Community
  • 1
  • 1
pilau
  • 6,635
  • 4
  • 56
  • 69
  • I don't understand the close votes - do people even read my question? It is not about which is better - it's about if it is technically possible. – pilau Jul 25 '13 at 18:58

2 Answers2

1

Sorry, didn't read your question right the first time.

NodeJS is a JavaScript engine with a bunch of libraries and an event loop. More specifically NodeJS uses the same JavaScript engine as Google Chrome (V8).

In JavaScript strings are primitive value types and moreover are immutable (as value types generally are). You are therefor passing a value and not a reference. It is impossible to change the value of a string inside a function in JavaScript.

var a = "Some String";
myFunction(a);
console.log(a);// We can know for sure that `a` is still "Some String"*

If this is still unclear you might want to check this question about how JavaScript passes variables around.

* Unless myFunction is defined in the same closure or has explicit access to the variable itself, even in such case, the string a itself did not change.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Oh yes, primitive values! I even remember reading the exact question you linked. Thanks :) – pilau Jul 25 '13 at 18:40
1

Go with the second one, as the first will not change the value of myPath, but rather return an new string that has been normalized. Or as another options

myPath = "my/path";
myPath = path.normalize(myPath);

I like this one only because it adds a little flexibility. Say later you want to do more with myPath prior to normalizing it. You can then leave the line doing the normalizing alone and add additional logic above. Mostly I'm just a fan of doing string assignments at the top of my function if possible...

Ironosity
  • 33
  • 1
  • 6