-3
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.

FeCH
  • 133
  • 3
  • 15
  • 3
    Variable `c` and `a` are pointing to the same value in memory, so every change on `c` will modify `a`. – Ele Mar 10 '18 at 19:15
  • 2
    This is `mutability`. Its is as @Ele says. So you need to make a new instance of the values for example with es6. c = [...a] – Nicholas Mar 10 '18 at 19:17
  • Try to use: `c = a.slice(0);` This allows you to deep-copy the array, so you won't modify a when modifying c. – Tostifrosti Mar 10 '18 at 19:21
  • @connexo Duplicates are still useful, because the ultimate reference may be too general, and the intermediate duplicate provides valuable context for converting the general answer to a specific one. – Raymond Chen Mar 10 '18 at 19:36

1 Answers1

1

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

yajiv
  • 2,901
  • 2
  • 15
  • 25