var a = [1,2,3]
var b = [4,5,6]
var c = a;
Why in the case of c[2] = b[0], the value of a[2] would also get changed?
As far as I understand var c = a
should only assign whatever value in a[]
to c[]
and not the other way around.
var a = [1,2,3]
var b = [4,5,6]
var c = a;
Why in the case of c[2] = b[0], the value of a[2] would also get changed?
As far as I understand var c = a
should only assign whatever value in a[]
to c[]
and not the other way around.
The basic rule in JavaScript is this: primitive types are manipulated by value, and reference types, as the name suggests, are manipulated by reference.
Numbers and Booleans are primitive types in JavaScript--primitive because the consist of nothing more than a small fixed number of bytes, bytes that are very easily manipulated at the low (primitive) levels of the JavaScript interpreter.
On the other hand, objects and arrays are reference types. These data types can contain arbitrary numbers of properties or elements, and so can be of arbitrary size, and cannot be so easily manipulated.
Since object and array values can become quite large, it doesn't make sense to manipulate these types by value, which could involve the inefficient copying and comparing of large amounts of memory.
For more info:- Read this