DEV Community

Eugene Karataev
Eugene Karataev

Posted on

References in JavaScript

I've been working with JavaScript for 4 years and I still meet interesting scenarios. The code below is a simplified example of the issue I faced recently in my day-to-day work.

let color = {value: 'brown'};

let cat = {color: color};

color = {value: 'white'};

console.log(cat); // ?
Enter fullscreen mode Exit fullscreen mode

Take a moment, read the code and think what the console.log output will be 🤔.

And the answer is

{
  color: {value: 'brown'}
}
Enter fullscreen mode Exit fullscreen mode

Wait. We know that in JS non-primitive variables are passed by reference. But it's obvious that cat object didn't change after colorvariable modification.

So, what's going on here? Let's analyze the code step by step.

First of all, we declare variable color, create a new object {value: 'brown} and assign this object to the color.

After that the new object {color: color} is created and it's assigned to the new variable cat.

In the end we create one more object {value: 'white'} and assign it to the existing variable color.

The question is: why the object cat hasn't changed?

❗ In JavaScript it's not possible for variables to reference other variables. It's possible in other languages, but not in JS.

After the 2nd line is executed, cat.color reference the {value: 'brown'} object, not the color variable. That's why assigning a new object to the color variable don't change the cat object.

Hope it makes sence. Stay curious and keep coding! 😎

P.S. Test yourself. What will be the output if we slightly change the code

let color = {value: 'brown'};

let cat = {color: color};

color.value = 'white';

console.log(cat); // ?
Enter fullscreen mode Exit fullscreen mode

Top comments (0)