ES6 Study Notes
From reading ECMAScript 6 by Ruanyf
‘let’
Variables declared using ‘let’ will only exist in the scope of its own code block.
{
let a = 10;
var b = 1;
}
a // ReferenceError: a is not defined.
b // 1
for loop works idealy well with let.
for (let i = 0; i < 10; i++) {}
console.log(i);
//ReferenceError: i is not defined
Example
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 10
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 6
for (let i = 0; i < 3; i++) {
let i = 'abc';
console.log(i);
}
// abc
// abc
// abc
if a ‘var’ variable has never been declared, its value is ‘undefined’, this is strange because it allows you to use variables that you has not been declared in the program. ‘let’ fixes this problem, ReferenceError will be caught if the programmer tries to use a ‘let’ variable that has not been initialised.
// var
console.log(foo); // Output: undefined
var foo = 2;
// let
console.log(bar); // Output: ReferenceError
let bar = 2;
var tmp = 123;
if (true) {
tmp = 'abc'; // ReferenceError
let tmp;
}
In the above example, a global variable tmp is initialsed with a value 123. in the code block of the if statement, the code tries to initialise a block scope variable ‘tmp’ again, which results an error.
{Block}
Anything inside ’{}’ is a block. ES6 allows multiple layers of blocks.
{{{{{let insane = 'Hello World'}}}}};
Variables from other blocks can’t be accessed.
{{{{
{let insane = 'Hello World'}
console.log(insane); // Error
}}}};
‘const’ type’s value cannot be modified once initialsed
const PI = 3.1415;
PI // 3.1415
PI = 3;
// TypeError: Assignment to constant variable.
Like ‘let’, ‘const’ can only be accessed within its code block.
const a = [];
a.push('Hello'); // valid
a.length = 0; // valid: clears the array
a = ['Dave']; // error
a is an array, the value of a cannot be assigned from another array.
Ways to declare variable
- var
- function
- let
- const
- import
- class
Window objects
window objects are like global objects.
window.a = 1;
a // 1
a = 2;
window.a // 2
let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3
let [ , , third] = ["foo", "bar", "baz"];
third // "baz"
let [x, , y] = [1, 2, 3];
x // 1
y // 3
let [head, ...tail] = [1, 2, 3, 4];
head // 1
tail // [2, 3, 4]
let [x, y, ...z] = ['a'];
x // "a"
y // undefined
z // []
let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"
let [foo] = [];
let [bar, foo] = [1];
let [x, y, z] = new Set(['a', 'b', 'c']);
x // "a"
let [foo] = [];
let [bar, foo] = [1];
In the above example, destructuring fails, ‘foo’ gets the value ‘undefined’
// Errors
let [foo] = 1;
let [foo] = false;
let [foo] = NaN;
let [foo] = undefined;
let [foo] = null;
let [foo] = {};
let [x = 1, y = x] = []; // x=1; y=1
let [x = 1, y = x] = [2]; // x=2; y=2
let [x = 1, y = x] = [1, 2]; // x=1; y=2
let [x = y, y = 1] = []; // ReferenceError