6. Arrow Function Syntax
() => { ... } // no parameter
x => { ... } // one parameter
(x, y) => { ... } // several parameters
x => { return x * x } // block
x => x * x // expression
6
8. var vs. let vs. const
function order(x, y) {
if (x > y) {
let tmp = x;
x = y;
y = tmp;
}
console.log(tmp===x);
// ReferenceError: tmp is not defined
return [x, y];
}
let works similarly to var, but
the variable it declares is
block-scoped, it only exists
within the current block. var
is function-scoped.
8
9. var vs. let vs. const
const foo;
// SyntaxError: missing = in const declaration
const bar = 123;
bar = 456; // TypeError: `bar` is read-only
const obj = {};
obj.prop = 123;
console.log(obj.prop); // 123
const works like let, but the variable
you declare must be immediately
initialised, with a value that can’t be
changed afterwards.
9
10. var vs. let vs. const
function logArgs(...args) {
for (const [index, elem] of
args.entries()) {
const message = index + '. ' +
elem;
console.log(message);
}
}
logArgs('Hello', 'everyone');
// Output:
// 0. Hello
// 1. everyone
10
11. var vs. let vs. const
const arr = [];
for (var i=0; i < 3; i++) {
arr.push(() => i);
}
arr.map(x => x()); // [3,3,3]
const arr = [];
for (let i=0; i < 3; i++) {
arr.push(() => i);
}
arr.map(x => x()); // [0,1,2]
11
21. Template Literals
21
const firstName = 'Jane';
console.log(`Hello ${firstName}!
How are you
today?`);
// Output:
// Hello Jane!
// How are you
// today?
22. Tagged template literals
22
tagFunction`Hello ${firstName} $
{lastName}!`
tagFunction(['Hello ', ' ', '!'],
firstName, lastName)
const str = String.raw`This is a text
with multiple lines.
Escapes are not interpreted,
n is not a newline.`;
23. Classes
23
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return `(${this.x}, ${this.y})`;
}
}
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y);
this.color = color;
}
toString() {
return super.toString() + ' in ' + this.color;
}
}
29. Use case 2: constants representing concepts
29
const COLOR_RED = Symbol('Red');
const COLOR_ORANGE = Symbol('Orange');
const COLOR_YELLOW = Symbol('Yellow');
function getComplement(color) {
switch (color) {
case COLOR_RED:
return COLOR_GREEN;
case COLOR_ORANGE:
return COLOR_BLUE;
case COLOR_YELLOW:
return COLOR_YELLOW;
default:
throw new Exception('Unknown color:
'+color);
}
}
30. for…in vs for…of
30
var arr = [ 3, 5, 7 ];
arr.foo = “hello";
for (var i in arr) {
console.log(i) // "0","1","2","foo"
}
for (var i of arr) {
console.log(i) // 3, 5, 7
}