Object and Arrays
A few quick examples:
Strings & Numbers
Numbers
let age = 100;
let age2 = age;
console.log(age, age2); // 100 100
age = 200;
console.log(age, age2); // 200 100
Strings
let name = 'Kieran';
let name2 = name;
console.log(name, name2); // Kieran Kieran
name = 'Kie';
console.log(name, name2); // Kie Kieran
Arrays
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];
// we want to make a copy of it.
const team = players;
console.log(players, team);
// You might think we can just do something like this:
// team[3] = 'Lux';
// However, this updates both arrays as it's not a copy but a reference to the original array.
We can get around this by using .slice(). Usually, you can pass values into slice to return one or more items. However, if you have an empty slice it will return a copy of the original array.
const team2 = players.slice();
Another way we can do this is by using .concat().
const team3 = concat(players);
Finally, you can also use the ES6 spread(...). This takes every items out of the iterable and put it in the containing array we just made.
const team4 = [...players];
Objects
const person = {
name: 'Wes Bos',
age: 80
};
// we make a copy:
// const captain = person;
// captain.number = 99;
This is the same as the arrays in that we have not made a copy but we have made a reference. Therefore number is now added to the person object.
Instead, to make a copy we use Object.assign().
const cap2 = Object.assign({} person, { number: 99 });
The way this works is that:
- You first start with a blank object.
- You pass it the object you wish to copy all the properties from.
- Lastly you fold in your new properties you wish to overwrite.
- Put it in its own variable and you have a copy of an object rather than a reference.
cap2 will now be:
cap2 = {
name: 'Wes Bos',
age: 80,
number: 99
};
// person will be unchanged:
person = {
name: 'Wes Bos',
age: 80
};