ES2020
JaxNode October 2020
History
- 1995 Version 1.0 Netscape (LiveScript)
- 1998, 99 Version 2.0 editorial, 3.0 RegEx, Try Catch
- Version 4 never happened, Think TypeScript
- 2009 Version 5 added map, filter and reduce functions as well as JSON and strict mode
ES2020
- JavaScript is actually EcmaScript
- ES6 became ES2015
- New features being added each year
Recent Changes
- import/export
- mjs/cjs modules
- Classes
- For-Of
- Const/Let
- Sets/Maps
- Generators
- ...Spread
More Recent Changes
- Better Random
- Rest(...parameter)
- default parameter = 0
- { destructered } = object
- Proxy object
- Symbol object
import / export
- Node supports Common.js and Module.js
- 'import' and 'export' keywords use Module.js
- Controversial
- .mjs extension has been the standard for using modules syntax
- .cjs for common.js using the 'require()' method
- Node 14 allows developers to set package.json 'type': 'module' to use the newer syntax
// addTwo.mjs
function addTwo(num) {
return num + 2;
}
export { addTwo };
// app.mjs
import { addTwo } from './addTwo.mjs';
// Prints: 6
console.log(addTwo(4));
Classes
- Java or C# for templating objects
- Controversial
- Java/C# are Class based Object Oriented
- JS are prototype based Object Oriented
- JS is more of a functional programming language
- JS Classes are not true classes
- Read Why Composition is harder with Classes by Eric Elliot
function Person(first, last, age) {
this.firstName = first;
this.lastName = last;
this.personAge = age;
return this;
}
Person.prototype.getFullname = function() {
return `${this.firstName} ${this.lastName}`;
}
Person.prototype.description = function() {
console.log(`${this.firstName} ${this.lastName} is ${this.personAge} years old.`)
}
class Person {
constructor(first, last, age) {
this.firstName = first;
this.lastName = last;
this.personAge = age;
}
getFullname() {
return `${this.firstName} ${this.lastName}`;
}
description() {
console.log(`${this.firstName} ${this.lastName} is ${this.personAge} years old.`)
}
}
function createPerson(first, last, age) {
function getFullname() {
return `${first} ${last}`;
}
function description() {
console.log(`${first} ${last} is ${age} years old.`);
}
return Object.freeze({
first,
last,
age,
getFullname,
description
});
}
For-Of
- Compliments For loops
- Will iterate over every value in an object as apposed to the iterator
let myArray = ['Dave', 'Piper', 'Harry', 'Scott'];
for (let i in myArray) {
console.log(myArray[i]);
}
for (let item of myArray) {
console.log(item);
}
Variable declarations
- 'var' hoists variable to global scope
- 'let' only works in its scope
- 'const' is like a readonly variable
Sets and Maps
- Sets similar to array, but no dups
- Maps are like hash-maps or dictionaries
let myMap = new Map([[ 'John', 34], ['Bill', 22], ['Burt', 79]);
myMap.set('Sarah', 29);
// You can also verify if there is a key value pair in your map
// by calling the has(key) function.
myMap.has('Sarah');
// You can return the value for a given key by using the get(key) function.
myMap.get('Sarah'); // returns 29;
Generators
- Asynchronously handle multiple results
- Generator object returned by Generator functions
- Conforms to the to both iterator and the iterable interface.
- '*' used at beginning of function
- 'yield' used to return iterations until end reached
"use strict";
function *getSomeValues() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
}
var someValues = getSomeValues();
console.log(someValues.next()); // yields { value: 1, done: false }
console.log(someValues.next()); // yields { value: 2, done: false }
console.log(someValues.next()); // yields { value: 3, done: false }
console.log(someValues.next()); // yields { value: 4, done: false }
console.log(someValues.next()); // yields { value: 5, done: false }
console.log(someValues.next()); // yields { value: undefined, done: true }
Spread operator
- Denoted by three periods
- ...arr
- Useful if you need to copy array
- Easier to concatenate
- let inner = [3, 4];
let merged = [0, 1, 2, ...inner, 5];
Rest Operator
- Denoted by three periods
- function(...array_of_params)
function listAnimalsES2015(...animals) {
animals.forEach(item => {
console.log(item);
});
}
listAnimalsES2015('dog', 'cat', 'platipus');
Default Parameters
- Define parameters with Default values
- function (a, b = 0, name = 'Bob')
- Prevents from having to use multiple method signatures
Destructuring
- Shorthand for assigning multiple values from an object or array
- Assign variables to on key names or array position
- Variables placed inside of '[]' or '{}'
- const [one, two, three] = array;
- const { lastName, age } = person;
2020 New Features
- Optional Chaining
- globalThis
- Dynamic Imports
- Promise.allSettled()
- Nullish Coalescing Operator
- BigInt
Optional chaining
- What are optionals
- ? operator
- Common in languages like Swift and C#
- Prevent undefined errors
let customer = {
name: “Carl”,
details: { age: 82 }
};
const customerCity = customer?.city ?? “Unknown city”;
console.log(customerCity); // Unknown city
let customer2 = {
name: "David",
details: { age: 50 },
city: 'Jacksonville'
}
const customerCity2 = customer2?.city ?? “Unknown city”;
console.log(customerCity2); // Jacksonville
globalThis
- Global scoped object
- Available everywhere in your app
- Helps bridging window, self and this
// browser environment
console.log(globalThis); // => Window {...}
// node.js environment
console.log(globalThis); // => Object [global] {...}
// web worker environment
console.log(globalThis); // => DedicatedWorkerGlobalScope {...}
Dynamic Imports
- Meant for the browser
- Allows to dynamically import an outside module
- Creates a promise
// Example from https://www.ksharifbd.com/blog/exploring-ES2020-dynamic-import/
<script type="module">
import add from './add.js';
add(7, 4); // returns 11
</script>
<!-- We don't need to set the type -->
<script>
import('./add.js')
.then(module => module.default(7, 4)) //returns 11
.catch(error => // log error);
</script>
// this code resides in subtract.js file
const subtract = (a, b) => a - b;
export { subtract };
// in index.js file
import('./subtract.js')
.then(module => module.subtract(7, 4)) // returns 3
.catch(error => // log error);
Promise allSettled
- Handles when all promises have settled
- Pass in an array of promises
- Solves the problem of notifying once all promises have completed
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];
Promise.allSettled(promises).
then((results) => results.forEach((result) => console.log(result.status)));
// expected output:
// "fulfilled"
// "rejected"
Nullish Coallessing Operator
- ??
- Double question mark operator
- Allows developer to set an alternate value if value is null or undefined
- const return = null ?? 'Default Value'
- Available in other languages like C# and Swift
BigInt
- New object for large integer values
- number object for generic ints and floats
- Normal integers are based on 32 bit values
- Can create with either BigInt constructor or placing 'n' after integer value
const theBiggestInt = 9007199254740991n
const alsoHuge = BigInt(9007199254740991)
// ↪ 9007199254740991n
const hugeString = BigInt("9007199254740991")
// ↪ 9007199254740991n
const hugeHex = BigInt("0x1fffffffffffff")
// ↪ 9007199254740991n
const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111")
// ↪ 9007199254740991n
Demo
One More Thing!
ES2021
- String.prototype.replaceAll
- Promise.any
- Logical Operators and Assignment Expressions &&=
- Numeric Separators 100_000
- Intl.ListFormat
- dateStyle and timeStyle options for Intl.DateTimeFormat
- Cure for COVID-19
Questions?
ES2020
By David Fekke
ES2020
- 826