Baumgartner - @Ddprrt - Nov 2020 Brendan Eich JS Had to “Look Like Java” Only Less So, Be Java’S Dumb Kid Brother Or Boy- Hostage Sidekick
Total Page:16
File Type:pdf, Size:1020Kb
Modern JavaScript Baumgartner - @ddprrt - Nov 2020 Brendan Eich JS had to “look like Java” only less so, be Java’s dumb kid brother or boy- hostage sidekick. Plus, I had to be done in ten days or something worse than JS would have happened. Java Perl HyperTalk Strings, Arrays, Syntax Event Handlers Regular Expressions Self Scheme AWK Prototype inheritance Closures functions Eich’s subversive Agenda • Objects without classes • First class functions • Closures • Prototypes • Some Java influences Eich’s subversive Agenda • Objects without classes var person = { name: "Stefan", • First class functions age: 38 } • Closures • Prototypes • Some Java influences Eich’s subversive Agenda • Objects without classes function greet(name) { alert("Hello " + name) • First class functions } • Closures function stefanize(funcs) { • Prototypes funcs("Stefan") } • Some Java influences stefanize(greet) Eich’s subversive Agenda • Objects without classes function greet(name) { return function(greeting) { • First class functions alert(greeting + ", " + name) • Closures } } • Prototypes greet("Stefan")("Salut") • Some Java influences Eich’s subversive Agenda • Objects without classes var lifeform = { Person.prototype = lifeform greet: function() { Dog.prototype = lifeform alert("Hello, " + this.name) • First class functions }, var stefan = new Person("Stefan") species: function() { stefan.greet() • Closures alert("I am a " + this.species) } var waldi = new Dog( } “Waldi”, “Dackel” • Prototypes ) function Person(name) { waldi.greet() this.name = name • Some Java influences this.species = "Human" } function Dog(name, kind) { this.name = name this.species = "Dog" this.kind = kind } Eich’s subversive Agenda • Objects without classes • First class functions • Closures • Prototypes • Some Java influences Eich’s subversive Agenda • Objects without classes !/ types as objects • First class functions var message = new String("Hello") • Closures • Prototypes • Some Java influences Eich’s subversive Agenda • Objects without classes !/ types as objects • First class functions var message = new String("Hello") • Closures !/ And the Y2K bug in Date • Prototypes • Some Java influences Eich’s subversive Agenda • Objects without classes !/ types as objects • First class functions var message = new String("Hello") • Closures !/ And the Y2K bug in Date • Prototypes • Some Java influences JavaScript is what comes after C if C++ never happened Stefan Baumgartner JavaScript is Lisp in C’s clothing. Bryan Cantrill 1995 JavaScript’s inception 1996 Introduction of JScript 1995 1996 1995 1997 ECMAScript Standardization 1996 1999 ECMAScript 3 RegEx, better String handling try/catch, etc. 1995 1997 1996 1999 1995 1997 2003 ECMAScript 4 abandoned Classes, interfaces, types, … 1996 1999 2009 ECMAScript 5 “strict” mode, property descriptors JSON, …. 1995 1997 2003 1996 1999 2009 1995 1997 2003 1996 1999 2009 1995 1997 2003 2015 ECMAScript 6 / ES2015 Classes, modules, better for loops Destructuring, Promises, Arrow functions Generators … 1996 1999 2009 1995 1997 2003 2015 1996 1999 2009 2016 2017 2018 1995 1997 2003 2015 https://www.ecma-international.org/activities/Languages/Language%20overview.pdf Modern JavaScript in Action Block scope assignments !/ ES5 !/ ES6+ var x = 0 let x = 0 if(someCondition) { if(someCondition) { var x = 1 let x = 1 } } console.log(x) !/ x != 1 console.log(x) !/ x != 0 Const assignments const x = "Stefan" const person = { name: "Stefan" x = 2 } !/ Uncaught TypeError: person.age = 38 !/ Assignment to constant variable. person.name = "Not Stefan" const assignments are block scoped const assignments are immutable reference assignments Objects, Arrays, Sets can still be mutated Destructuring const position = [10, 20] const x = position[0] const y = position[1] !/ Destructuring! const [x, y] = position const [a, b, !!.rest] = [1, 2, 3, 4, 5]; !/ rest operator !!. console.log(a); !/ 1 console.log(b); !/ 2 console.log(rest); !/ [3, 4, 5] Destructuring function getPosition() { return { x: 50, y: 200, z: 13 }; } const { x, y } = getPosition(); !/ renames const { z : zIndex } = getPosition(); !/ defaults const { a = 0 } = getPosition(); Object creation !/ 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 !/ ES6+ const name = "Stefan"; const age = 38; const person = { name, age, whoami() { !/ String template literals return `I am ${this.name} and I am ${this.age} years old` } } Template literals can have any expression within ${} and are multiline for loops for (let value of myArray) { !/ !!. } for (let index of myArray.keys()) { !/ !!. } for (let [index, value] of myArray.entries()) { !/ !!. } for (let key in myObject) { } Functions !/ Default parameters function setVAT(price, vat = 0.2) { return price * (1 + vat) } !/ Destructuring function printPerson({ name, age }) { !/!!. } !/ Rest arguments function recursivePrint(el, !!.rest) { console.log(el); recursivePrint(rest) } recursivePrint(1, 2, 3, 4, 5, 6) 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 Spread operator !/ passing arguments as list fn(1, 2, 3) !/ as array fn(!!.[1, 2, 3]) !/ concatenation !/ z != [1, 2, 3, 4, 5, 6, 7] const z = [1, 2, !!.[3, 4, 5], 6, 7] !/ cast lists to arrays const imgs = [!!.document.querySelectorAll("img")] !/ merge Objects const person = { !!.nameAndAge, !!.personFunctions } Classes !/ ES5 !/ ES6+ function Car () { class Car { this.fuel = 0; constructor () { this.distance = 0; this.fuel = 0 } this.distance = 0 } Car.prototype.move = function () { move () { this.fuel!-; this.distance += 2; this.fuel!-; this.distance += 2; } } addFuel () { Car.prototype.addFuel = function () { this.fuel!+; this.fuel!+ } } } 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 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…) 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 TypeScript Baumgartner - @ddprrt - Nov 2020 1100001010100011 49827 -15709 £ … What is a type? A type is a classification of data that defines the operations that can be done on that data, the meaning of the data, and the set of allowed values. Vlad Riscutia 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 Does JavaScript have types http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf Type Hierarchy in JavaScript https://exploringjs.com/impatient-js/ch_values.html Type Hierarchy in TypeScript TypeScript is a superset of JavaScript TS JS 1996 1999 2009 2016 2017 2018 1995 1997 2003 2015 ECMAScript 6 / ES2015 1996 1999 2009 2016 2017 2018 1995 1997 2003 2011 TypeScript’s inception 2015 ECMAScript 6 / ES2015 Anders Hejlsberg https://channel9.msdn.com/Shows/Going+Deep/Anders-Hejlsberg-and-Lars-Bak-TypeScript-JavaScript-and-Dart TypeScript is JavaScript! ⭐ 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 ⭐ 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. ⛩ Gradual, structural, generic ( Distinct value / type namespaces ) Extensive type inference * Control flow analysis & Object-oriented and functional Gradual typing 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) } /** * @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) } 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; const defaultOrder = { This object