0

Test 1:

var arr1 = [10, 20]; var arr2 = arr1; arr2[0]++; alert(arr1);// [11, 20] --- What?!?! alert(arr2);// [11, 20] --- correct 

Test 2:

var arr1 = [10, 20]; var arr2 = [arr1[0], arr1[1]]; arr2[0]++; alert(arr1);// [10, 20] --- correct alert(arr2);// [11, 20] --- correct 

In test 1, Why the first array's first element was changed? As far as I know, in other OOP languages like Java & PHP, if we do the Test 1's var arr2 = arr1; this is called "referencing", once we change something with the new variable's value, it creates a new value for that so the first reference "arr1" doesn't get effected. Why it's not the same thing in Javascript!? This totally doesn't make sense! Is it a bug? or it's just that Javascript behaves differently?

1
  • 1
    Look up "javascript deep copy" vs "javascript shallow copy" Commented Jun 29, 2014 at 0:25

2 Answers 2

3

JavaScript variables refer to objects. When a variable "is" an object, it contains a reference to the object. Assigning the value of such a variable to another variable just transfers the reference; it does not make a copy of the referenced object.

Sign up to request clarification or add additional context in comments.

Comments

1

In the Test 1 both variables are referencing the same array object, so anything you do on one is going to be reflected on the other one.

On the other hand, on the Test 2 you are copying the values into a new array, so each variable is referencing different array objects.

edit: to remove the "passby" term.

edit 2: on a side note, this happens in java too.

5 Comments

This is really not correct. There's no "passing" happening here. The terms "pass by value" and "pass by reference" have to do with the semantics of function calls.
As a side-note, an easier way to copy the values is arr2 = arr1.slice(0);.
lol, true passing means as parameters in a function/method, but its the same idea.
@EdwardM.B. it's a related concept, but strictly speaking they're really two completely different things.
Lots of languages do this. The big exceptions are truly functional languages where data's immutable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.