2

I am learning Javascript and in W3 schools' code editor I try the following code :

    <!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var cars = ["Saab", "Volvo", "BMW"];
var newcars = [];
newcars = cars;
newcars[0] = "Benz"
document.getElementById("demo").innerHTML = cars[0];
</script>

</body>
</html>

I expected the value to be : "Saab" since I made no changes to the cars array and the only change was to the newcars array, yet the output was : "Benz".

Could someone please explain what is happening?

Thanks

anotherDev
  • 195
  • 4
  • 13

3 Answers3

4

If you want to clone the cars array, use slice:

var newcars = cars.slice(0);

Otherwise they will point to the same array (by reference) in memory.

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
1

You are using the same reference.

var cars = ["Saab", "Volvo", "BMW"];
var newcars = []; // new array! good!
newcars = cars; // points to cars. all changes will reflect both.
newcars[0] = "Benz"
document.getElementById("demo").innerHTML = cars[0];

You may want to copy the array and not the reference. If your using Jquery than this is good:

// Shallow copy
var newObject = jQuery.extend([], oldObject);

// Deep copy
var newObject = jQuery.extend(true, [], oldObject);
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
1

The value of variable "cars" contains a "reference to the array" not "the array value". So, when you go like "var newcars = cars" you are actually copying the reference only, which means that "cars" and "newcars" are pointing to the same array. You need to make another copy of the array which "cars" points to and then let the "newcars" reference to that new copy. You can clone an array in different ways, it could be done using libraries like jQuery (like here), underscore (like here) or without like in here Copying array by value in JavaScript

Community
  • 1
  • 1
Qusai Jouda
  • 1,048
  • 8
  • 12
  • yes the behaviour is similar, in JavaScript every thing is passed by value, but one should notice that with Arrays and Objects the value is the reference. – Qusai Jouda Jun 10 '14 at 14:00