-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlet-const.js
59 lines (40 loc) · 989 Bytes
/
let-const.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
/** Let && Const **/
// ES5
var foo = 'Mr.Foo'
// var variables are function-scoped,
// mainly their innermost enclosing function.
function func (flag) {
if (flag) {
var foo = 'NewFoo'
return foo
}
return foo
}
func(true) // NewFoo
func(false) // undefined
// ES6
// Use let
let foo = 'Mr.Foo'
// let variables are block-scoping
// i.e. they live in their defined block.
function func (flag) {
if(flag) {
// new block scope
let foo = 'NewFoo'
return foo
// end block scope
}
return foo
}
func(true) // NewFoo
func(false) // Mr.Foo
// Use const
const foo = 'Mr.Foo'
// const are the try for constant values,
// i.e. immutable values
// however, only the assignment is immutable.
foo = 'NewFoo' // ERROR - No new assignment allowed.
// An interesting example
const bar = { a : 3 }
bar = { b : 7} // ERROR - No new assignment allowed.
bar.a = 7 // OK - We are updating a property, not the assignment.