Skip to content

Commit

Permalink
Finalizando o dia 14
Browse files Browse the repository at this point in the history
  • Loading branch information
herminiotorres committed Jul 14, 2018
1 parent 4886880 commit 15554e3
Showing 1 changed file with 58 additions and 1 deletion.
59 changes: 58 additions & 1 deletion 14-JavaScriptReferencesVSCopying/finish.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,28 @@

<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 = 'Wes';
let name2 = name;
console.log(name, name2);
name = 'wesley';
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(players, team);
// You might think we can just do something like this:

team[3] = 'Lux';
console.log(players, team);
// however what happens when we update that array?

// now here is the problem!
Expand All @@ -26,12 +40,26 @@
// 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] = 'Fred';
console.log(players, team2);
const team3 = [].concat(players);
team3[3] = 'David';
console.log(players, team3);

// one way

// or create a new array and concat the old one in

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

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


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

Expand All @@ -44,13 +72,42 @@
};

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

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

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

// 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 wesbos = {
name: 'WesBos',
age: 60,
social: {
twitter: '@wesbos',
facebook: 'wesbos.developer'
}
};
console.log(wesbos);

const developer = Object.assign({}, wesbos);
console.log(developer);
developer.name = 'Wesley';
console.log(developer, wesbos);

developer.social.twitter = '@coolman';
console.log(developer, wesbos);

const developer2 = JSON.parse(JSON.stringify(wesbos));
developer2.social.twitter = '@awesomeman';
console.log(developer2, wesbos);

</script>

</body>
Expand Down

0 comments on commit 15554e3

Please sign in to comment.