Skip to content

Commit bc8bb4c

Browse files
committed
Array & Object copy and ref wesbos#14
1 parent 1856f0b commit bc8bb4c

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

14 - JavaScript References VS Copying/index-START.html

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,16 @@
3131

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

34+
const concatPlayers = [].concat(players)
35+
concatPlayers[3] = "Tobi"
36+
console.log(concatPlayers)
37+
3438
// or use the new ES6 Spread
3539

40+
const spreadPlayers = [...players]
41+
spreadPlayers[3] = "Tobi"
42+
console.log(spreadPlayers)
43+
console.log(players)
3644
// now when we update it, the original one isn't changed
3745

3846
// The same thing goes for objects, let's say we have a person object
@@ -44,6 +52,15 @@
4452
};
4553

4654
// and think we make a copy:
55+
const parsePerson = JSON.parse(JSON.stringify(person))
56+
console.log(parsePerson)
57+
const spreadPerson = {...person}
58+
console.log(spreadPerson)
59+
60+
person.age = 21
61+
spreadPerson.age = 25
62+
63+
console.log(`Person is ${person.age} years old, while spread person is ${spreadPerson.age} years old`)
4764

4865
// how do we take a copy instead?
4966

0 commit comments

Comments
 (0)