Is there a way to know that 2 javascript variable point to the same memory address ?
var my_var = {
id: 1,
attribute: "myAttribute"
}
var copy = my_var;
//someting like
if(copy === my_var) return true;
Is there a way to know that 2 javascript variable point to the same memory address ?
var my_var = {
id: 1,
attribute: "myAttribute"
}
var copy = my_var;
//someting like
if(copy === my_var) return true;
You can't alias variables like you can in C. In javascript, something like
var x = 1;
var y = x
y = 4;
// x is still 1
will always be the case.
However, objects are always passed by reference
var x = { one: 1, two: 2 };
var y = x;
y.one = 100;
// x.one is now 100
Is there a way to know if 2 javascript variable point to the same memory address ?
Generally the answer is no. Primitive types (like numbers) are being passed around by value. So we have
> var x = 1;
> var y = 1;
> x === y;
true
even though they don't refer to the same memory location (well, this is an implementation detail, but they are not pointing to the same memory address at least in V8).
But when both sides are objects then yes: use ==
or ===
. If both sides are objects then each operator checks whether they point at the same memory address.
> var x = {test: 1};
> var y = {test: 1};
> x === y;
false
In javascript when we declare more than one variable with same value then each and every variable points same memory location.Basically javascript follow the reference counting algorithm.same things happen in Python.
In Python, you can use id(variableName)
to get the memory address:
>>> x = "hello world"
>>> id(x)
4347327152
>>> x = 2
>>> id(x)
4305328544
But I don't know the how to achieve it in JavaScript. Otherwise, we can also easily see whether two pointers point to the same address. Hopefully my answer provides some useful information.