Modern JavaScript Baumgartner - @ddprrt - Nov 2020 Brendan Eich JS - - PowerPoint PPT Presentation

modern javascript
SMART_READER_LITE
LIVE PREVIEW

Modern JavaScript Baumgartner - @ddprrt - Nov 2020 Brendan Eich JS - - PowerPoint PPT Presentation

Modern JavaScript Baumgartner - @ddprrt - Nov 2020 Brendan Eich JS had to look like Java only less so, be Javas dumb kid brother or boy- hostage sidekick. Plus, I had to be done in ten days or something worse than JS would have


slide-1
SLIDE 1

Modern JavaScript

Baumgartner - @ddprrt - Nov 2020

slide-2
SLIDE 2

Brendan Eich

slide-3
SLIDE 3

JS had to “look like Java” only less so, be Java’s dumb kid brother or boy- hostage sidekick.

slide-4
SLIDE 4

Plus, I had to be done in ten days or something worse than JS would have happened.

slide-5
SLIDE 5

Java

Syntax

Perl

Strings, Arrays, Regular Expressions

AWK

functions

Self

Prototype inheritance

Scheme

Closures

HyperTalk

Event Handlers

slide-6
SLIDE 6

Eich’s subversive Agenda

  • Objects without classes
  • First class functions
  • Closures
  • Prototypes
  • Some Java influences
slide-7
SLIDE 7

Eich’s subversive Agenda

  • Objects without classes
  • First class functions
  • Closures
  • Prototypes
  • Some Java influences

var person = { name: "Stefan", age: 38 }

slide-8
SLIDE 8

Eich’s subversive Agenda

  • Objects without classes
  • First class functions
  • Closures
  • Prototypes
  • Some Java influences

function greet(name) { alert("Hello " + name) } function stefanize(funcs) { funcs("Stefan") } stefanize(greet)

slide-9
SLIDE 9

Eich’s subversive Agenda

  • Objects without classes
  • First class functions
  • Closures
  • Prototypes
  • Some Java influences

function greet(name) { return function(greeting) { alert(greeting + ", " + name) } } greet("Stefan")("Salut")

slide-10
SLIDE 10

Eich’s subversive Agenda

  • Objects without classes
  • First class functions
  • Closures
  • Prototypes
  • Some Java influences

var lifeform = { greet: function() { alert("Hello, " + this.name) }, species: function() { alert("I am a " + this.species) } } function Person(name) { this.name = name this.species = "Human" } function Dog(name, kind) { this.name = name this.species = "Dog" this.kind = kind } Person.prototype = lifeform Dog.prototype = lifeform var stefan = new Person("Stefan") stefan.greet() var waldi = new Dog( “Waldi”, “Dackel” ) waldi.greet()

slide-11
SLIDE 11

Eich’s subversive Agenda

  • Objects without classes
  • First class functions
  • Closures
  • Prototypes
  • Some Java influences
slide-12
SLIDE 12

Eich’s subversive Agenda

  • Objects without classes
  • First class functions
  • Closures
  • Prototypes
  • Some Java influences

/0 types as objects var message = new String("Hello")

slide-13
SLIDE 13

Eich’s subversive Agenda

  • Objects without classes
  • First class functions
  • Closures
  • Prototypes
  • Some Java influences

/0 types as objects var message = new String("Hello") /0 And the Y2K bug in Date

slide-14
SLIDE 14

Eich’s subversive Agenda

  • Objects without classes
  • First class functions
  • Closures
  • Prototypes
  • Some Java influences

/0 types as objects var message = new String("Hello") /0 And the Y2K bug in Date

slide-15
SLIDE 15

Stefan Baumgartner

JavaScript is what comes after C if C++ never happened

slide-16
SLIDE 16

JavaScript is Lisp in C’s clothing.

Bryan Cantrill

slide-17
SLIDE 17

JavaScript’s inception

1995

slide-18
SLIDE 18

1996

Introduction of JScript

1995

slide-19
SLIDE 19

1996 1995

ECMAScript Standardization

1997

slide-20
SLIDE 20

1996 1995 1997 1999

ECMAScript 3 RegEx, better String handling try/catch, etc.

slide-21
SLIDE 21

1996 1995 1997 1999

ECMAScript 4 abandoned Classes, interfaces, types, …

2003

slide-22
SLIDE 22

1996 1995 1997 1999 2003 2009

ECMAScript 5 “strict” mode, property descriptors JSON, ….

slide-23
SLIDE 23

1996 1995 1997 1999 2003 2009

slide-24
SLIDE 24

1996 1995 1997 1999 2003 2009

ECMAScript 6 / ES2015 Classes, modules, better for loops Destructuring, Promises, Arrow functions Generators …

2015

slide-25
SLIDE 25

1996 1995 1997 1999 2003 2009 2015

slide-26
SLIDE 26

2017 1996 1995 1997 1999 2003 2009 2015 2016 2018

slide-27
SLIDE 27

https://www.ecma-international.org/activities/Languages/Language%20overview.pdf

slide-28
SLIDE 28
slide-29
SLIDE 29

Modern JavaScript in Action

slide-30
SLIDE 30

/0 ES5 var x = 0 if(someCondition) { var x = 1 } console.log(x) /0 x => 1

Block scope assignments

/0 ES6+ let x = 0 if(someCondition) { let x = 1 } console.log(x) /0 x => 0

slide-31
SLIDE 31

const x = "Stefan" x = 2 /0 Uncaught TypeError: /0 Assignment to constant variable.

Const assignments

const person = { name: "Stefan" } person.age = 38 person.name = "Not Stefan"

const assignments are block scoped const assignments are immutable reference assignments Objects, Arrays, Sets can still be mutated

slide-32
SLIDE 32

const position = [10, 20] const x = position[0] const y = position[1] /0 Destructuring! const [x, y] = position const [a, b, ../rest] = [1, 2, 3, 4, 5]; /0 rest operator ../ console.log(a); /0 1 console.log(b); /0 2 console.log(rest); /0 [3, 4, 5]

Destructuring

slide-33
SLIDE 33

function getPosition() { return { x: 50, y: 200, z: 13 }; } const { x, y } = getPosition(); /0 renames const { z : zIndex } = getPosition(); /0 defaults const { a = 0 } = getPosition();

Destructuring

slide-34
SLIDE 34

/0 ES5 var name = "Stefan"; var age = 38; var person = { name: name, age: age, whoami: function() { return "I am " + this.name + " and I am " + this.age + "years old" } }

Object creation

slide-35
SLIDE 35

/0 ES6+ const name = "Stefan"; const age = 38; const person = { name, age, whoami() { /0 String template literals return `I am ${this.name} and I am ${this.age} years old` } }

Object creation

Template literals can have any expression within ${} and are multiline

slide-36
SLIDE 36

for loops

for (let value of myArray) { /0 ../ } for (let index of myArray.keys()) { /0 ../ } for (let [index, value] of myArray.entries()) { /0 ../ } for (let key in myObject) { }

slide-37
SLIDE 37

Functions

/0 Default parameters function setVAT(price, vat = 0.2) { return price * (1 + vat) } /0 Destructuring function printPerson({ name, age }) { /0../ } /0 Rest arguments function recursivePrint(el, ../rest) { console.log(el); recursivePrint(rest) } recursivePrint(1, 2, 3, 4, 5, 6)

slide-38
SLIDE 38

Arrow functions

const shout = (name) =? name.toUpperCase()

Arrow functions are strictly anonymous Adding a block { } after the arrow requires a return statement Wrap objects in parens to return them immediately Arrow functions are lexical scoped: this is either module scope, class scope, or last function scope

slide-39
SLIDE 39

Spread operator

/0 passing arguments as list fn(1, 2, 3) /0 as array fn(../[1, 2, 3]) /0 concatenation /0 z => [1, 2, 3, 4, 5, 6, 7] const z = [1, 2, ../[3, 4, 5], 6, 7] /0 cast lists to arrays const imgs = [../document.querySelectorAll("img")] /0 merge Objects const person = { ../nameAndAge, ../personFunctions }

slide-40
SLIDE 40

/0 ES5 function Car () { this.fuel = 0; this.distance = 0; } Car.prototype.move = function () { this.fuel-.; this.distance += 2; } Car.prototype.addFuel = function () { this.fuel+, }

Classes

/0 ES6+ class Car { constructor () { this.fuel = 0 this.distance = 0 } move () { this.fuel-.; this.distance += 2; } addFuel () { this.fuel+,; } }

slide-41
SLIDE 41

Notes on classes

Classes are

  • Syntactic sugar for prototype / constructor function Object generation
  • A more convenient way to add getters, setters, and private properties
  • A more convenient way to add to the prototype chain via extends

Classes are not

  • A type
  • An abstraction
  • Java
slide-42
SLIDE 42

Things left out

  • Maps, Sets, WeakMaps, WeakSets
  • New functions in Array, Object, Number, String
  • Reflection, Proxies, generator functions
  • Symbols and Iterators
  • ECMAScript modules
  • async / await and Promises (we might do that in live coding…)
slide-43
SLIDE 43

Wrapping up

  • JavaScript is not a toy language anymore —> powerful constructs!
  • ECMAScript standards are released once per year
  • Objects and functions are still at the heart of JavaScript, it just gets more

conventient

  • Convenience functions are idiomatic —> use them
slide-44
SLIDE 44

TypeScript

Baumgartner - @ddprrt - Nov 2020

slide-45
SLIDE 45

1100001010100011

49827

  • 15709

£ …

slide-46
SLIDE 46

What is a type?

slide-47
SLIDE 47

A type is a classification of data that defines the

  • perations that can be done on that data, the

meaning of the data, and the set of allowed values.

Vlad Riscutia

slide-48
SLIDE 48

Typing is checked by the compiler and/or run time to ensure the integrity of the data, enforce access restrictions, and interpret the data as meant by the developer.

Vlad Riscutia

slide-49
SLIDE 49

Does JavaScript have types

slide-50
SLIDE 50

http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf

slide-51
SLIDE 51

https://exploringjs.com/impatient-js/ch_values.html

Type Hierarchy in JavaScript

slide-52
SLIDE 52

Type Hierarchy in TypeScript

slide-53
SLIDE 53

TS

TypeScript is a superset of JavaScript

JS

slide-54
SLIDE 54

2017 1996 1995 1997 1999 2003 2009

ECMAScript 6 / ES2015

2015 2016 2018

slide-55
SLIDE 55

2017 1996 1995 1997 1999 2003 2009

ECMAScript 6 / ES2015

2015 2016 2018 2011

TypeScript’s inception

slide-56
SLIDE 56

Anders Hejlsberg

slide-57
SLIDE 57
slide-58
SLIDE 58
slide-59
SLIDE 59

https://channel9.msdn.com/Shows/Going+Deep/Anders-Hejlsberg-and-Lars-Bak-TypeScript-JavaScript-and-Dart

slide-60
SLIDE 60

TypeScript is JavaScript!

slide-61
SLIDE 61

⭐ Open Source and Open Development " Closely track ECMAScript standard # Innovate in type system $ Best of breed tooling ⏬ Continually lower barrier to entry & Community, community, community

slide-62
SLIDE 62

⭐ TypeScript IS JavaScript ⭐ Language innovation through ECMAScript ⭐ Type system innovation through use cases ⭐ Tooling as prime citizen

Non-goal: Apply a sound or "provably correct" type system. Instead, strike a balance between correctness and productivity.

slide-63
SLIDE 63

⛩ Gradual, structural, generic ( Distinct value / type namespaces ) Extensive type inference * Control flow analysis & Object-oriented and functional

slide-64
SLIDE 64

Gradual typing

slide-65
SLIDE 65

function addVAT(price, vat) { return price * (1 + vat) // Oh! You add and multiply with numbers, so it's a number } addVAT2(2, 0.2).toUpperCase() // Immediate Krawutzikaputzi function addVAT(price, vat = 0.2) { // great, `vat`is also number! return price * (1 + vat) } /** * Adds VAT to a price * * @param {number} price The price without VAT * @param {number} vat The VAT [0-1] * * @returns {number} */ function addVAT(price, vat = 0.2) { return price * (1 + vat) }

slide-66
SLIDE 66

/** * @typedef {Object} Article * @property {number} price * @property {number} vat * @property {string} string * @property {boolean=} sold */ /** * Now we can use Article as a proper type * @param {[Article]} articles */ function totalAmount(articles) { return articles.reduce((total, article) => { return total + addVAT(article) }, 0) }

slide-67
SLIDE 67

function addVAT(price: number, vat: number): number { return price * (1 + vat) } // or: declare, don’t implement (aka Header file, file comes from a different lib) declare function addVAT(price: number, vat: number): number;

slide-68
SLIDE 68

const defaultOrder = { articles: [ { price: 1200.50, vat: 20, title: 'Macboox Air Refurbished - 2013' }, { price: 9, vat: 0, title: 'I feel smashing subscription' } ], customer: { name: 'Fritz Furball', address: 'Smashing Hill, 90210', dateOfBirth: new Date(2006, 9, 1) } } This object would make a good type type Order = typeof defaultOrder; function checkOrders(orders: Order[]) { return orders.reduce((valid, order) => { return valid && order.articles.length > 0 }, true) } typeof creates types on the fly

slide-69
SLIDE 69

What’s const in JS?

slide-70
SLIDE 70

const gift = { price: 0, vat: 0, title: 'A bottle opener', } as const; // gift.price = 100; // this breaks const context makes true const objects

slide-71
SLIDE 71

Structural vs nominal typing

slide-72
SLIDE 72

Duck Typing

slide-73
SLIDE 73

interface Named { name: string; } class Person { name: string; } let p: Named; // OK, because of structural typing p = new Person(); interface Named { name: string; } let x: Named; // y's inferred type is { name: string; location: string; } let y = { name: "Alice", location: "Seattle" }; x = y;

slide-74
SLIDE 74

Type namespaces

slide-75
SLIDE 75

primitive types

number string boolean Symbol Object null undefined

slide-76
SLIDE 76

number string boolean Symbol Object null undefined

top types

any unknown

slide-77
SLIDE 77

number string boolean Symbol Object null undefined

bottom types

never

slide-78
SLIDE 78

primitive types

number string boolean Symbol Object null undefined

slide-79
SLIDE 79

primitive types

number string boolean null undefined

slide-80
SLIDE 80

value types

number string boolean null undefined true false

  • 1

1000000 NaN 6 120.3 … … ‘Hello world’ ‘Baumi’

slide-81
SLIDE 81

value types

true false

  • 1

1000000 NaN 6 120.3 … … ‘Hello world’ ‘Baumi’ null undefined

slide-82
SLIDE 82

value types

number string boolean true false

  • 1

1000000 NaN 6 120.3 … … ‘Hello world’ ‘Baumi’ null undefined

slide-83
SLIDE 83

number | string | undefined

number string boolean true false

  • 1

1000000 NaN 6 120.3 … … ‘Hello world’ ‘Baumi’ null undefined

slide-84
SLIDE 84

Intersection types

{ a: string } { b: string } { a: string, b: string }

slide-85
SLIDE 85

type Talk = { speaker: string, title: string, abstract: string } type TechEvent = { title: string, description: string date: Date, capacity: number, rsvp: number } We want to create Tech events that are tech events, but a little bit more type Meetup = TechEvent & { type: 'meetup' location: string, price: 'free', talks: Talk[] } type Conference = TechEvent & { type: 'conference', location: string, price: number, talks: Talk[] } type Webinar = TechEvent & { type: 'webinar', url: string, videoUrl: string, talks: Talk } Intersection types! type TechEvents = Webinar | Conference | Meetup; Union types!

slide-86
SLIDE 86

Generics

slide-87
SLIDE 87

declare class Widget { toJSON(): { kind: "Widget", date: Date } } type Item = { text: string; count: number; choice: "yes" | "no" | null; func: () => void; nested: { isSaved: boolean; data: [1, undefined, 2]; } widget: Widget; children: Item[]; } declare let item: JSONified<Item>; type JSONified<T> = JSONifiedValue<T extends { toJSON(): infer U } ? U : T>; type JSONifiedValue<T> = T extends string | number | boolean | null ? T : T extends Function ? undefined : T extends Array<infer U> ? JSONifiedArray<U> : T extends object ? JSONifiedObject<T> : undefined; type UndefinedAsNull<T> = T extends undefined ? null : T; interface JSONifiedArray<T> extends Array<UndefinedAsNull<JSONified<T>>> {} type JSONifiedObject<T> = { [P in keyof T]: JSONified<T[P]> }

slide-88
SLIDE 88

type AllElements = { 'a': HTMLAnchorElement; 'div': HTMLDivElement; 'span': HTMLSpanElement; 'ul': HTMLUListElement; 'title': HTMLTitleElement; 'textarea': HTMLTextAreaElement; 'template': HTMLTemplateElement; 'tfoot': HTMLTableSectionElement; 'thead': HTMLTableSectionElement; 'tbody': HTMLTableSectionElement; 'tr': HTMLTableRowElement; 'table': HTMLTableElement; 'col': HTMLTableColElement; 'colgroup': HTMLTableColElement; 'th': HTMLTableHeaderCellElement; 'td': HTMLTableDataCellElement; 'caption': HTMLTableCaptionElement; 'style': HTMLStyleElement; 'select': HTMLSelectElement; 'script': HTMLScriptElement; 'blockquote': HTMLQuoteElement; 'q': HTMLQuoteElement; } Map types type JSXHTMLElement<T extends keyof AllElements> = AllElements[T]; type JSXElement<T extends string> = T extends keyof AllElements ? JSXHTMLElement<T> : HTMLElement; Mapped types Conditional types

slide-89
SLIDE 89

Control flow analysis

slide-90
SLIDE 90

function shouting(param: any) { if(typeof param === 'string') { // i am a string return param.toUpperCase() } else if(typeof param === 'number') { // i am a number return `${param}`.toUpperCase() } return 'I HAVE NO IDEA WHAT TO DO' }

slide-91
SLIDE 91

And classes…

slide-92
SLIDE 92

class Vendor { name: string; constructor(name: string) { this.name = name; } greet() { return "Hello, welcome to " + this.name; } } Which parts are JS, which are TS? class FoodTruck extends Vendor { cuisine: string; constructor(name: string, cuisine: string) { super(name); this.cuisine = cuisine; } greet() { return "Hi, welcome to food truck " + this.name + ". We serve " + this.cuisine + " food."; } }

slide-93
SLIDE 93

✅ Gradual, structural, generic ✅ Distinct value / type namespaces ✅ Extensive type inference ✅ Control flow analysis ✅ Object-oriented and functional