0

Hello

i lost about 4 hours debugging strange issue

my work flow was

var config = {
  someKey : [
    'valueA','valueB'
  ]
};

function anAction()
{
  // some code and loops like a maze, then
  async.each(config.someKey,function(configKey)
  {
    // another maze+asynchronous , and because off my bad luck i use configKey inside if statement and change it
  });
}

so after the loop async.each change my config values like if it's call by reference

so my question if it's default behaviour in javascript to use call by reference or it's async behaviour ?

Edit

it's not related to async

please test this example

var crazy = [
  {key:'value'}
];

// safe code no change
crazy.forEach(function(item)
{
  item = 'new value';
});
console.log(crazy);

// bad code do change
crazy.forEach(function(item)
{
  item.key = 'new value';
});
console.log(crazy);
Bdwey
  • 1,813
  • 1
  • 16
  • 18
  • 1
    JavaScript is **always** call-by-value. It's unclear to be what your issue is, but I guess it's related to the fact that objects are *mutable* and that objects are passed *as* reference. – Felix Kling May 15 '15 at 22:22
  • so in this case why it's pass by reference ? – Bdwey May 15 '15 at 23:32
  • As I said, JavaScript is always call-by-value, implying that it is not pass by reference. Whatever your issue is, it's not because JavaScript passes something by reference. It may be because JS passes objects **as** references. But since your example is reduced to a point where it is incomplete and you are not describing what result you get and what you expect, there is not really much more to say about it. – Felix Kling May 15 '15 at 23:34
  • you are right i test scenario inside stand alone file and it work as expected call-by-value i will check it again and edit my question i use SailsJS maybe it's related to something else – Bdwey May 16 '15 at 03:17
  • 1
    Hmm... I'd like to note that this "duplicate" is a strange case. The questions are not actually duplicates but my accepted answer is the answer to this question (also, please read the comments to that answer as well since they include a nice discussion of the edge case I mention at the bottom of my answer) – slebetman May 16 '15 at 03:58
  • Regarding your edit: That's how JavaScript works. `item.key = 'new value';` mutates the object referenced by `item` and assigns a new value to its `key` property. The simplest case to replicate is `var foo = {bar: 42}; foo.bar = 21; console.log(foo.bar); // logs 21`. – Felix Kling May 16 '15 at 04:30
  • @slebetman you got a great investigation to this issue even if it's mutates object what it's unchanged in the first example item should reference to the same pointer as it's object ! – Bdwey May 16 '15 at 04:39
  • @FelixKling no this example not the case. as it's normal behaviour , please open you mind to this comment http://stackoverflow.com/a/13508654/1029833 – Bdwey May 16 '15 at 04:43

0 Answers0