-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathvariable-es6.js
99 lines (77 loc) · 2.31 KB
/
variable-es6.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
*
* ES6 has introduced two new keyword 'let' and 'const' for declaring variables
* So basically 'let' and 'const' are new alternative of 'var' for declaring variables
*/
/**
* let
*
* let declares local variable for the nearest enclosing block
* let has been in Firefox for a long time and is now a part of ES6.
*
* References:
* https://github.com/sgaurav/understanding-es6/blob/master/let.js
*/
(function (myArray) {
for(let i = 0; i<myArray.length; i++) {
// variable i is declared only for this scope
// i is undefined outside the loop
// do something with myArray[i]
}
console.log("i is "+typeof i); // undefined
let foo = 10;
var foo = 1; // can't redeclare let variables in the same scope
})([1,2,3]);
/**
*
* Difference between 'let' and 'var' Keyword
*
* A variable defined using a var statement is known throughout the function it is defined in
* A variable defined using a let statement is only known in the block it is defined in
* 'var' declarations are hoisted and 'let' declarations are not hoisted
*
* References:
* http://stackoverflow.com/questions/762011/let-keyword-vs-var-keyword
*/
function loop(arr) {
// i IS NOT known here
// j IS NOT known here
for( var i = 0; i < arr.length; i++ ) {
// i IS known here
};
// i IS known here
// j IS NOT known here
for( let j = 0; j < arr.length; j++ ) {
// j IS known here
};
// i IS known here
// j IS NOT known here
}
loop( [1,2,3] );
/**
* The const statement creates a read-only constant.
* const variables must be declared using an initializer, const foo = 'bar'
* You can't override the value, still you can change object properties or array members
*
*
* NOTE:
* Constants can be declared with uppercase or lowercase, but a common
* convention is to use all-uppercase letters.
*
* References:
* https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/const
*/
(function(){
// Declare constants in Uppercase
const MAX_SIZE = 10;
MAX_SIZE = 20; // Error, can't override the value
// const requires an initializer
const FOO; // SyntaxError, it should be const FOO = "Some value";
// you can change object properties
const CONFIG = {
CLUSTER_SIZE: 4
}
CONFIG = 8;; // ERROR
CONFIG.CLUSTER_SIZE = 8; // NO ERROR
console.log(CONFIG); // Object {CLUSTER_SIZE: 8}
})();