-
Notifications
You must be signed in to change notification settings - Fork 3
/
constVsFreeze.js
68 lines (47 loc) · 1.37 KB
/
constVsFreeze.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
var canAlligatorsFly = false;
function isItFlying() {
canAlligatorsFly = true;
if (canAlligatorsFly) {
console.log("Yeah I'm flying");
}
}
isItFlying(); // Yeah I'm flying
const alligatorColor = "green";
function getMyColor() {
alligatorColor = "yellow"; // This part throws an error
return alligatorColor;
}
//const just prevents reassignment but doesn't forbid changing
const reptiles = ['alligators', 'crocs'];
reptiles.push('snakes');
console.log(reptiles); // ['alligators', 'crocs', 'snakes']
const alligator = {
canItFly: false
};
alligator.canItFly = true;
console.log(alligator.canItFly); // true
//Object.freeze() prevents modification or extension to the existing value of an object.
let alligator4 = {
canItFly: false
};
Object.freeze(alligator);
alligator.canItFly = true;
console.log(alligator.canItFly); // false, the value is not modified
//A quick note though, Object.freeze does allow reassignment:
let alligator2 = {
canItFly: false
};
Object.freeze(alligator);
alligator = {
pi: 3.14159
};
console.log(alligator) // {pi: 3.14159}
const alligator3 = {
canItFly: false
};
Object.freeze(alligator);
alligator.canItFly = true; // This is ignored
alligator = {
pi: 3.14
}; // This will throw an TypeError
console.log(alligator); // {canItFly: false}