Friday, February 1, 2013

JavaScript, passing-by-reference and slice()

Some time ago I had a problem with arrays and assignments. I was working with a distributed system in JavaScript; the root process sent some "work" to do to some subprocesses (workers) and those returned an array as result, which was modified inside the callback of the dispatching function.

The issue was that when I modified the array, I then assigned it to a variable and passed it to a function. The problem was that while I was working in the callback with this array, it got modified somehow. I later understood that the problem was due to the fact that JavaScript passes values by reference. That is basically the array I assigned to the variable before passing it to the function was simply saving it's reference on the variable, but not really duplicating it.

The following example will show the problem.

var arr = [1, 2, 3]

var arr2 = arr;

arr2[0] = 0;


//prints 0

As shown, this prints zero. To solve the issue I used a custom procedure to copy every single value of the array into a new one. This is pretty painful and later I discovered I could simply use the slice() function. The following snippet based on the previous example will show the black magic:

var arr = [1, 2, 3]

var arr2 = arr.slice();

arr2[0] = 0;


//prints 1

Basically that's it. It's a very naive problem, and a skilled programmer may quickly find the issue, but knowing the existence of the slice() function may save quite some time.

1 comment:

  1. For the price and the reliability that comes with the movement, I am ok with this slight rolex replica uk in the design, but some others might find it unacceptable. The selling point for me with replica watches is the thick stainless steel case paired with a scratch resistant. If you can follow regatta racing and are clear on some of the physical rigors involved for people or replica watches on board one of these vessels in a race. For anyone who has ever been on a boat and I am not talking cruiseship here, a boat is a horrible place for a nice replica watches sale which this is except the price. You will bang it to crap and it will look like dog shite in no time. This pointless gimmicky rolex replica sale is the last thing you need while running in a highly competitive race and the 2017 rolex replica is the cherry on this really expensive tofuty cake.