loading...
Cover image for Arrays and Objects Are Passed By Reference

Arrays and Objects Are Passed By Reference

samelawrence profile image Sam E. Lawrence Updated on ・1 min read

Arrays and objects are passed by reference. This is something that can catch a lot of beginners out and lead to some frustrating bugs. For example:

let fruit = ["apple", "pear", "orange"];
let food = fruit;
food.push("chicken");

console.log(fruit); // ["apple", "pear", "orange", "chicken"]
console.log(food); // ["apple", "pear", "orange", "chicken"]

To get around this we can ensure that we create a new array that copies the values of the first, using the spread operator, like so:

let fruit = ["apple", "pear", "orange"];
let food = [...fruit];
food.push("chicken");

console.log(fruit); // ["apple", "pear", "orange"]
console.log(food); // ["apple", "pear", "orange", "chicken"]

The same problem can arise with objects:

let fruit = {a: "apple"};
let food = fruit;
food.b = "banana";

console.log(fruit); // {a: "apple", b: "banana"}
console.log(food); // {a: "apple", b: "banana"}

Again, we solve for this issue with passing by reference by using the Object.assign() method. Note that we must initialize an empty object and then pass in the first object as the second parameter to fill it.

let fruit = {a: "apple"};
let food = Object.assign({}, fruit);
food.b = "banana";

console.log(fruit); // {a: "apple"}
console.log(food); // {a: "apple", b: "banana"}

These mindbenders are like learning idioms in a human language, little quirks built into the language.

What are some of your favorite weird things about Javascript?

Posted on by:

Discussion

markdown guide