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

0

3 Answers 3

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.

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

Comments

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

1 Comment

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.
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);

1 Comment

for an array should that not be jQuery.extend([], oldObject); ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.