I am working on leveling up my javascript skills and like to learn by building things. So I was working on a simple javascript game as an experiment. When I figured out something weird you could do with object manipulation that kind of made my head screwy. You can reference one object within another and manipulate both of them simultaneously. Let's have a look at some code here.
Can I get a reference
Below I declare 2 variables. however the value of one variable is the other variable.
Let original = "unique string";
Let reference = original;
If you were to log out the value of these variables they would be identical. The same is also true for objects with nested properties.
let theOriginal = {stuff :'unique string', another : ‘second unique string’}
let theReference = theOriginal
Now if you log out theReference
you will get the same key/values as theOriginal
.
You can take this one step further and manipulate a value.
let theOriginal = {stuff :'unique string',
Another: ‘second unique string’}
let theReference = theOriginal
theReference.stuff = 'other string’
Console.log(theOriginal.stuff)
// will now log ‘other string’
Ok whats going on here?
When I first learned Manipulating one variable affects the other in this way it kind of made my head spin. I was thinking about each variable as being its own separate thing. This however is not true. The reason this works is because in the actual physical memory of the computer this is running on there is really only one object. This object is referenced by 2 different variables. Much like having 2 doors to the same cabinet. If you add something to the cabinet with 1 door when the other door opens there will be a new item there.
Why do this?
You can add many more references to the same object as you want. Though this adds a lot of unnecessary complexity to your code. There are few use cases where it really makes sense to do this. For me, my use case was a turn based game where each player object takes a turn being the active player. Having the active variable just reference the player object meant any changes made to the active object during the turn would already be represented in the player object.
I think this is a cool tid bit of knowledge that really expanded my understanding of javascript as a whole. Below is a code pen where I experimented with this concept.
I want to thank you for reading this through and I hope you found this article helpful in some way.
Top comments (0)