X Tutup
Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions 14 - JavaScript References VS Copying/index-START.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,33 @@

<script>
// start with strings, numbers and booleans
let age = 100;
let age2 = age;
console.log(age, age2);

age = 200;

console.log(age, age2);

let name = "Lex";
let name2 = name;
console.log(name, name2);

name = "Alex";

console.log(name, name2);

// Let's say we have an array
const players = ['Wes', 'Sarah', 'Ryan', 'Poppy'];

// and we want to make a copy of it.
const team = players;

console.log(team, players);

// You might think we can just do something like this:
// team[3] = 'Lex';
// console.log(team, players);

// however what happens when we update that array?

Expand All @@ -25,26 +45,63 @@
// Why? It's because that is an array reference, not an array copy. They both point to the same array!

// So, how do we fix this? We take a copy instead!
const team2 = players.slice();
team2[3] = 'Lex';
console.log(team2, players);

// one way

// or create a new array and concat the old one in
const team3 = [].concat(players);
team3[3] = 'Shemp';
console.log(team3, players);

// or use the new ES6 Spread
const team4 = [...players];
team4[3] = 'Larry';
console.log(team4, players);

const team5 = Array.from(players);
team5[3] = 'Moe';
console.log(team5, players);

// now when we update it, the original one isn't changed

// The same thing goes for objects, let's say we have a person object

// with Objects
const person = {
name: 'ASAP',
age: '99',
};

// and think we make a copy:
// const captain = person;
// captain.number = 99;
// console.log(captain, person);

// how do we take a copy instead?
const captain2 = Object.assign({}, person, { number: 99, age: '12' } );
console.log(captain2, person);

// We will hopefully soon see the object ...spread
const captain3 = {...person};
captain3.number = 27;
console.log(captain3, person);

// Things to note - this is only 1 level deep - both for Arrays and Objects. lodash has a cloneDeep method, but you should think twice before using it.
const lex = {
name: "lex",
age: 101,
social: {
twitter: '@asapountzis',
facebook: 'secretgeek',
}
};
console.clear();
console.log(lex);

const dev = Object.assign({}, lex);

</script>

Expand Down
X Tutup