Reputation: 358
I know this topic has come up a few times, but I couldn't find a conclusive answer/confirmation to what JavaScript references actually are.
The fundamental concepts I know so far are mainly reference variables (a variable that stores a reference) and Aliases (a variable which translates to the same memory address).
When looking at this tutorial, the main take-away seems: https://medium.com/@naveenkarippai/learning-how-references-work-in-javascript-a066a4e15600
When the compound value in a variable is reassigned, a new reference is created. In JavaScript, unlike in most other popular programming languages, the references are pointers to value stored in variables and NOT pointers to other variables, or references.
This sounds very similar to the concept of Aliases. I know you can't compare JavaScript with C++, but conceptually speaking.
So let me sum up and tell me if I am right - or otherwise feel free to correct me:
It does not point to another variable, but to its value == the variable holds the object itself?
let a = { a: 4 }
let b = a
Accessing a reference means simply calling the variable, as it pretty much holds the object itself - no dereferencing necessary. Assigning a reference will need to check the type of variable 'a' first to see if it is an object and then set up 'b' with 'a's target address.
So 'a' and 'b' are just Aliases for the same variable.
Upvotes: 0
Views: 76
Reputation: 664185
JavaScript doesn't have "reference variables" or "alias variables" "variable aliases"1. All JS variables are independent, and they can hold arbitrary values of any type.
When we talk about references in JS, we mean reference values. Consider them to work like C++ shared_ptr
s (except that garbage collection does not work by refcounting).
It does not point to another variable, but to its value
Kinda, yes. Both variables hold a reference value that references the same object. The assignment b = a
created a copy of the reference value. Reassigning a
to a different value (whether it is a different reference, or a primitive value like a number or null
) will not affect b
.
So 'a' and 'b' are just Aliases for the same variable.
No. At best, they are aliases for the same object, since they both reference the same memory location where the { a: 4 }
is stored. That memory location is not a variable though, it's allocated in managed memory.
1: Module imports are real aliases though. When you import { example as local } from …
, then local
identifier resolves to the same variable (memory location) as example
in the module that exports it. Changing the value of the example
variable is reflected in local
. The local
import cannot be assigned to, though.
Upvotes: 2