professional-programming/training/front-end/01-modern-javascript.md

285 lines
7.0 KiB
Markdown
Raw Normal View History

2020-07-21 09:37:15 +02:00
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
## Table of Contents
2020-07-21 11:59:24 +02:00
- [Modern JavaScript](#modern-javascript)
2020-07-21 09:37:15 +02:00
- [Quirks](#quirks)
- [Printing and interacting with the console](#printing-and-interacting-with-the-console)
- [Comparing scalar, arrays, and objects](#comparing-scalar-arrays-and-objects)
- [Always use triple comparators (`===`) instead of double (`==`)](#always-use-triple-comparators--instead-of-double-)
- [Comparing non-scalar](#comparing-non-scalar)
- [`Object` methods](#object-methods)
- [`Object.assign`, spread operator](#objectassign-spread-operator)
- [`Array` methods](#array-methods)
- [`Array.includes` (ES7)](#arrayincludes-es7)
- [Object literals, assignment and destructuring](#object-literals-assignment-and-destructuring)
- [Objects](#objects)
- [Array](#array)
- [`let` and `const`](#let-and-const)
- [Arrow functions](#arrow-functions)
- [How `this` works in arrow functions](#how-this-works-in-arrow-functions)
- [Best practices](#best-practices)
- [Classes](#classes)
- [Prototypal inheritance](#prototypal-inheritance)
- [Template literals](#template-literals)
- [Template tags](#template-tags)
- [Loops](#loops)
- [`for... of`](#for-of)
- [Promises](#promises)
- [Creating a promise](#creating-a-promise)
- [Consuming a promise](#consuming-a-promise)
- [Chaining promises](#chaining-promises)
- [Async functions](#async-functions)
- [Modules](#modules)
- [References](#references)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
2020-07-21 11:59:24 +02:00
# Modern JavaScript
2020-07-20 17:49:56 +02:00
Note: run code quickly with https://codesandbox.io/s/
## Quirks
2020-07-20 18:12:51 +02:00
### Printing and interacting with the console
```javascript
// Do not leave console.log in your code! There are linters such as eslint that will check for their absence
console.log("hello");
```
2020-07-20 17:49:56 +02:00
### Comparing scalar, arrays, and objects
#### Always use triple comparators (`===`) instead of double (`==`)
```javascript
// ???
2020-07-21 09:14:24 +02:00
console.assert("1" == 1);
2020-07-20 17:49:56 +02:00
// Better
2020-07-21 09:14:24 +02:00
console.assert(!("1" === 1));
console.assert("1" !== 1);
2020-07-20 17:49:56 +02:00
```
#### Comparing non-scalar
Applied on arrays and objects, `==` and `===` will check for object identity, which is almost never what you want.
```javascript
2020-07-21 09:14:24 +02:00
console.assert({ a: 1 } != { a: 1 });
console.assert({ a: 1 } !== { a: 1 });
2020-07-20 17:49:56 +02:00
2020-07-21 09:14:24 +02:00
const obj = { a: 1 };
const obj2 = obj;
console.assert(obj == obj2);
console.assert(obj === obj2);
2020-07-20 17:49:56 +02:00
```
Use a library such as [lodash](https://lodash.com/) to properly compare objects and array
```javascript
2020-07-21 09:14:24 +02:00
import _ from "lodash";
2020-07-20 17:49:56 +02:00
2020-07-21 09:14:24 +02:00
console.assert(_.isEqual({ a: 1 }, { a: 1 }));
console.assert(_.isEqual([1, 2], [1, 2]));
2020-07-20 18:12:51 +02:00
```
### `Object` methods
#### `Object.assign`, spread operator
`Object.assign` (ES 2015)
### `Array` methods
2020-07-20 17:49:56 +02:00
2020-07-20 18:12:51 +02:00
#### `Array.includes` (ES7)
2020-07-20 17:49:56 +02:00
2020-07-20 18:12:51 +02:00
## Object literals, assignment and destructuring
2020-07-20 17:49:56 +02:00
### Objects
```javascript
2020-07-21 09:14:24 +02:00
const toaster = { size: 2, color: "red", brand: "NoName" };
2020-07-20 17:49:56 +02:00
// Get one object key
2020-07-21 09:14:24 +02:00
const { size } = toaster;
console.assert(size === 2);
2020-07-20 17:49:56 +02:00
// Get the rest with ...rest
2020-07-21 09:14:24 +02:00
const { color, brand, ...rest } = toaster;
console.assert(_.isEqual(rest, { size: 2 }));
2020-07-20 18:12:51 +02:00
// Set default
2020-07-21 09:14:24 +02:00
const { size2 = 3 } = toaster;
console.assert(size2 === 3);
2020-07-20 18:12:51 +02:00
// Rename variables
2020-07-21 09:14:24 +02:00
const { size: size3 } = toaster;
console.assert(size3 === 2);
2020-07-20 18:12:51 +02:00
// Enhances object literals
2020-07-21 09:14:24 +02:00
const name = "Louis";
const person = { name };
console.assert(_.isEqual(person, { name: "Louis" }));
2020-07-20 18:12:51 +02:00
// Dynamic properties
2020-07-21 09:14:24 +02:00
const person2 = { ["first" + "Name"]: "Olympe" };
console.assert(_.isEqual(person2, { firstName: "Olympe" }));
2020-07-20 18:12:51 +02:00
// Btw, you can include quotes although nobody does this
2020-07-21 09:14:24 +02:00
console.assert(_.isEqual(person2, { firstName: "Olympe" }));
2020-07-21 12:08:28 +02:00
// Short form function
const es5Object = {
say: function () {
console.log("hello");
},
};
es5Object.say()
const es6Object = {
say() {
console.log("hello");
},
};
es6Object.say()
2020-07-20 17:49:56 +02:00
```
### Array
```javascript
const theArray = [1, 2, 3];
const [first, second] = theArray;
const [first1, second2, ...rest] = theArray;
console.assert(first === 1);
console.assert(second === 2);
console.assert(_.isEqualWith(rest, [3]));
```
## `let` and `const`
```javascript
2020-07-21 09:14:24 +02:00
const constantVar = "a";
2020-07-20 17:49:56 +02:00
// Raises "constantVar" is read-only
2020-07-21 09:14:24 +02:00
constantVar = "b";
2020-07-20 17:49:56 +02:00
2020-07-21 09:14:24 +02:00
let mutableVar = "a";
mutableVar = "a";
2020-07-20 17:49:56 +02:00
// Note: this will work ok
2020-07-21 09:14:24 +02:00
const constantObject = { a: 1 };
constantObject.a = 2;
constantObject.b = 3;
2020-07-20 17:49:56 +02:00
// Raises: "constantObject" is read-only
2020-07-21 09:14:24 +02:00
constantObject = { a: 1 };
2020-07-20 17:49:56 +02:00
// const and let are block scoped. A block is enclosed in {}
{
2020-07-21 09:14:24 +02:00
const a = "a";
console.log({ a });
2020-07-20 17:49:56 +02:00
}
// Raises: ReferenceError: a is not defined
2020-07-21 09:14:24 +02:00
console.log({ a });
2020-07-20 17:49:56 +02:00
```
Note: try to use `const` as much as you can.
- More constraints = safer code
- Some kind of "immutability" is good (since `const` objects can be modified, it is not true immutability)
- You can't define a `const` without providing its initial value
- Most people do this in modern JS
Never use `var`:
- `var` variables are initialized with `undefined`, while `let` and `const` vars are not initialized and will raise an error if used before definition.
- `var` is globally or function-scoped, depending on whether it is used inside a function.
- `let` and `const` are block-scoped
- `let` and `const` cannot be reused for the same variable name
## Arrow functions
The first advantage of arrow function is that they're shorter to write:
```javascript
// You can define a function this way:
2020-07-21 09:14:24 +02:00
const myFunction = function () {
2020-07-20 17:49:56 +02:00
console.log("hello world");
2020-07-21 09:14:24 +02:00
};
2020-07-20 17:49:56 +02:00
// With an arrow function, you save a few characters:
const myArrowFunction = () => {
console.log("hello world");
2020-07-21 09:14:24 +02:00
};
2020-07-20 17:49:56 +02:00
// Some things, like params parentheses, and function code brackets, are optional
2020-07-21 09:14:24 +02:00
const myFunctionToBeShortened = function (a) {
2020-07-20 17:49:56 +02:00
return a;
2020-07-21 09:14:24 +02:00
};
2020-07-20 17:49:56 +02:00
// Shorter arrow function
const myFunctionToBeShortenedArrowV1 = (a) => {
return a;
2020-07-21 09:14:24 +02:00
};
2020-07-20 17:49:56 +02:00
// Shortest arrow function
// Remove single param parenthesis, remove function code bracket, remove return
2020-07-21 09:14:24 +02:00
const myFunctionToBeShortenedArrowV2 = (a) => a;
console.assert(myFunctionToBeShortenedArrowV2(1) === 1);
2020-07-20 17:49:56 +02:00
```
2020-07-20 18:12:51 +02:00
### How `this` works in arrow functions
### Best practices
2020-07-20 17:49:56 +02:00
- I usually keep the parameters parenthesis. If you add a parameter, you'll have to add them back.
2020-07-20 18:12:51 +02:00
## Classes
### Prototypal inheritance
## Template literals
2020-07-21 12:08:28 +02:00
```javascript
const longString = `multi
line
string`;
const name = "Louis";
// Template interpolation
const hello = `Hello ${name}`;
```
2020-07-20 18:12:51 +02:00
### Template tags
## Loops
### `for... of`
Note: prefer using some functional constructs such as `map`, `reduce`, etc.
## Promises
### Creating a promise
### Consuming a promise
### Chaining promises
## Async functions
## Modules
CommonJS syntax:
ES Module syntax:
- default export and imports
- renaming imports
2020-07-20 17:49:56 +02:00
## References
- [ES5 to ESNextheres every feature added to JavaScript since 2015](https://www.freecodecamp.org/news/es5-to-esnext-heres-every-feature-added-to-javascript-since-2015-d0c255e13c6e/)
2020-07-21 12:08:28 +02:00
- [ES2015 / ES6: Basics of modern Javascript](https://www.slideshare.net/WojciechDzikowski/es2015-es6-basics-of-modern-javascript)