Spooky Action at a Distance in JavaScript

Tim Williams
2 min readJan 15, 2022

Einstein came up with the phrase ‘spooky action at a distance’ to describe quantum entanglement. The observation is that entangled particles can affect each other without any physical link between them. Move an entangled particle near you two inches and its sister particle millions of miles away will move exactly the same.

The way objects and scope and pass-by-reference works in JavaScript can make it feel a little like quantum entanglement. Consider this example.

Let’s say this is the setup of our application, we have two lists, a list of cars, then a list of cars by manufacturer. Finally we add our sample car to the manufacturer.

Consider the following modification.

What do you expect to happen to the other two variables?

This phenomenon isn’t unique to JavaScript, it’s called pass-by-reference, and it is a common paradigm in modern programming languages. It isn’t quite as simple as that though.

Consider this naive example:

Suddenly the problem becomes closer to the ‘Monty Hall Problem.’

I would expect in a true pass-by-reference language to modify the original reference to with my variable car with the updated object I created, but instead I accidentally lost the reference to the original variable by re-assigning it within the function scope.

The same phenomenon exists outside the function scope. In the example below I might assume that carRef is a pointer to car and when I update car, my carRef is updated as well. Instead what happens is I lose my original reference when assigning car to a new object and it has become a new pointer where carRef is a pointer to the originally defined object.

Since JavaScript has no facility for explicitly managing pointers, you have to be careful about how you are declaring your variable. If I had declared car as a const I could have avoided losing the reference by accidentally reassigning car.

The moral of the story with JavaScript is, if you are creating a complicated program, you should be very careful about how you define variables since it is easy to lose a reference (when you want the ‘spooky action at a distance’). It’s also easy to accidentally modify a referenced object thinking that it is a copy within the scope that you’re working.

--

--

Tim Williams
Tim Williams

Written by Tim Williams

I am a Web Developer passionate about new technologies, as well as time tested best practices (here’s looking at you Uncle Bob).

No responses yet