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?
Top comments (0)