Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6898a10

Browse files
Cloning by Reference and Shallow Cloning
1 parent 849ceb1 commit 6898a10

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

‎9_Value_vs_Reference/script.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// const animals = ["dogs", "cats"];
2+
3+
// const otherAnimals = animals;
4+
5+
// animals.push("pig");
6+
7+
// console.log(animals); // [ 'dogs', 'cats', 'pig' ]
8+
// We get the same output for otherAnimals too,
9+
// because the otherAnimals is also referencing the same memory
10+
// as the animals.
11+
// console.log(otherAnimals); // [ 'dogs', 'cats', 'pig' ]
12+
13+
// Cloning Arrays
14+
// 1st way : Spread Operator
15+
const numbers = [1, 2, 3, 4];
16+
const copiedNumbers = numbers;
17+
18+
// Using spread Opeator,
19+
// Also known as Shallow Cloning
20+
const newNumbers = [...numbers];
21+
22+
numbers.push(5);
23+
console.log(numbers); // [ 1, 2, 3, 4, 5 ]
24+
console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ]
25+
console.log(newNumbers); // [ 1, 2, 3, 4 ]
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
#### Copy by Reference
2+
3+
```js
4+
const animals = ["dogs", "cats"];
5+
6+
const otherAnimals = animals;
7+
8+
animals.push("pig");
9+
10+
console.log(animals); // [ 'dogs', 'cats', 'pig' ]
11+
// We get the same output for otherAnimals too,
12+
// because the otherAnimals is also referencing the same memory
13+
// as the animals.
14+
console.log(otherAnimals); // [ 'dogs', 'cats', 'pig' ]
15+
16+
// The behaviour is same even with respect to objects.
17+
```
18+
19+
#### Shallow Cloning
20+
21+
```js
22+
// Cloning Arrays
23+
// 1st way : Spread Operator
24+
const numbers = [1, 2, 3, 4];
25+
const copiedNumbers = numbers;
26+
27+
// Using spread Opeator,
28+
// Also known as Shallow Cloning
29+
const newNumbers = [...numbers];
30+
31+
numbers.push(5);
32+
console.log(numbers); // [ 1, 2, 3, 4, 5 ]
33+
console.log(copiedNumbers); // [ 1, 2, 3, 4, 5 ]
34+
console.log(newNumbers); // [ 1, 2, 3, 4 ]
35+
```
36+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /