JavaScript: The Magic Parts

JavaScript: The Magic Parts

How do I write JavaScript.

Fcebe976d7c72e909e987826f4a07eb8?s=128

Hannes Moser

October 21, 2016
Tweet

Transcript

  1. JavaScript:
 The Magic Parts Hannes Moser

  2. –Douglas Crockford If a feature is sometimes useful and sometimes

    dangerous and if there is a better option then
 always use the better option.
  3. –Hannes Moser I am going to use any feature I

    am able find within the language!
  4. –Douglas Crockford I made every mistake with
 JavaScript you could

    make.
  5. Libraries

  6. Modules modulecounts.com

  7. npm Modules modulecounts.com

  8. Modules modulecounts.com

  9. npm install pad-left

  10. npm install yolo

  11. npm install swag

  12. choo react, redux & saga lodash yo-yo

  13. ∞ Libraries

  14. absurdjs.com

  15. Object Literals

  16. Object Literals const a = 1 const b = 2

    const o = { a, b, c() { return 'I am C3PO' } }
  17. Functional Programing

  18. Arrow Functions const a = [1, 2, 3, 4, 5,

    6] const sumOfIncrementByOneAndOddNumbers = a .map(v => v += 1) .filter(v => v % 2 !== 0 ? v : false) .reduce((sum, v) => sum + v, 0) // 15
  19. Modules

  20. Modules: Export export default { run } export const G

    = 9.81
  21. Modules: Import import athlete from 'athlete' import {G} from 'athlete'

    const a = athlete.run() / G
  22. Template Strings

  23. Template Strings const foo = 'Hello' const bar = 'World'

    console.log(`${foo}, ${bar}!`)
 // Hello, World!
  24. Tagged Template Strings import html from 'html' const lftCol =

    html`<div class="col-sm-6">left</div>` const rgtCol = html`<div class="col-sm-6">right</div>` const dom = html` <div class="container"> <div class="row"> ${lftCol} ${rgtCol} </div> </div> ` document.body.appendChild(dom)
  25. Destructuring

  26. Destructuring const [a, b] = [1, 2, 3]
 // a

    === 1, b === 2
  27. Destructuring const {a, b} = {a:1, b:2}
 // a ===

    1, b === 2
  28. Destructuring: Fail-soft const [a, b = 2] = [1]
 //

    a === 1, b === 2
  29. Destructuring: Nesting const {op:a, lhs:{op:b}, rhs:c} = ast()

  30. Defaults

  31. Defaults function trim(str, char = ' ') { … }

    trim(' lala land ')
  32. Magic Parts

  33. Named Parameters

  34. Named Parameters function complex(name, priority, user, title) { … }

    complex(
 „Hannes Moser",
 undefined,
 null,
 „Mag.(FH)„
 ) // I like this more complex({ name: "Hannes Moser",
 title: "Mag.(FH)" })
  35. Named Parameters import assign from 'lodash/assign' function (config) { config

    = assign({baseurl: '/'}, config) }
  36. Named Parameters function url({baseurl: '/'}) { … } url({})

  37. Named Parameters function url({baseurl: '/'} = {}){ … } url()

    // "/"
  38. Class-free Objects

  39. Class-free Objects: Prototypes function Pokemon(name) { this.name = name //

    handle ... } Pokemon.prototype.collect = function() { … } const pikachu = new Pokemon("Pikachu")
  40. Class-free Objects: ES2015 Classes class Pokemon { constructor(name) { this.name

    = name // handle ... } collect() { … } } const pikachu = new Pokemon("Pikachu")
  41. Class-free Objects: Constructor Function function pokemon({name} = {}) { function

    collect() { … } return { collect } } const pikachu = pokemon({name: 'Pokemon'})
  42. Class-free Objects: Parasitic Inheritance import parasite from 'parasite' function pokemon({name}

    = {}) { const super = parasite({name}) function collect() { … } super.collect = collect return } const pikachu = pokemon({name: ‚Pokemon'}) pikachu.eat() && pikachu.collect()
  43. Clean Interfaces

  44. Clean Interfaces export default function pokemon() { function collect() {

    … } return {collect} } const pikachu = pokemon() pikachu.bad = function() { … } // no problem at all
  45. Clean Interfaces: Freeze export default function pokemon() { function collect()

    { … } return Object.freeze({collect}) } const pikachu = pokemon() pikachu.bad = function() { … } // throws TypeError or fails silently
  46. Ain't No Party Like a Third-Party JavaScript Party

  47. Malwaretising import $ from 'jquery' // your friendly malvertising service

    const pref = $.post $.post = function(...args) { pref({ url: 'https://example.com' }) return pref.call(null, ...args) } // example $.post({ url: 'https://example.net' })
  48. Malvertising malware.html

  49. Unicode

  50. Unicode const ಠ_ಠ = "uhu" console.log(ಠ_ಠ) // "uhu"

  51. for-of

  52. for-of const a = [1, 2] for([idx, val] of a.entries())

    { console.log(idx, val) }
  53. mandatory parameters

  54. mandatory parameters function mandatory() { throw new Error("Missing Parameter") }

    function foo(a = mandatory()) { … } foo() // Error: Missing Parameter
 foo(1)
  55. mixins

  56. mixins const Validation = Sup => class extends Sup {

    validate(schema) { … } } class Person { … } class Employee extends Validation(Person) { … }
  57. that’s not async

  58. that’s not async const file = open('hannes.json') const result =

    process(file) const html = render(result) html .then(str => console.log(str)) .catch(err => console.error(err))
  59. that’s not async function open(file) { return new Promise((resolve, reject)

    => { fs.readFile(file, (err, data) => { if (err) { return reject(err) } return resolve(data) }) }) }
  60. async/await const file = await open('hannes.json') const result = process(file)

    const html = render(result) console.log(html)
  61. Thank You

  62. Sources • ECMAScript® 2016 Language Specification • Douglas Crockford: The

    Better Parts • Axel Rauschmayr: 2ality.com, Exploring ES6 • Rebecca Murphy: Ain't No Party Like a Third-Party JavaScript Party • Snippets: https://github.com/eliias/the-magic-parts