Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
JavaScript: The Magic Parts
Search
Hannes Moser
October 21, 2016
Programming
0
140
JavaScript: The Magic Parts
How do I write JavaScript.
Hannes Moser
October 21, 2016
Tweet
Share
More Decks by Hannes Moser
See All by Hannes Moser
Docker
eliias
0
500
HTTPS Everywhere
eliias
1
270
Digitales Zeitalter
eliias
0
73
The full-stack education paradoxon
eliias
2
120
The FullStack Education Paradox
eliias
1
62
I 💖teaching
eliias
1
130
Other Decks in Programming
See All in Programming
月刊 競技プログラミングをお仕事に役立てるには
terryu16
1
1.2k
Fibonacci Function Gallery - Part 2
philipschwarz
PRO
0
210
선언형 UI에서의 상태관리
l2hyunwoo
0
270
Асинхронность неизбежна: как мы проектировали сервис уведомлений
lamodatech
0
1.3k
カンファレンス動画鑑賞会のススメ / Osaka.swift #1
hironytic
0
170
ErdMap: Thinking about a map for Rails applications
makicamel
1
650
PicoRubyと暮らす、シェアハウスハック
ryosk7
0
220
Lookerは可視化だけじゃない。UIコンポーネントもあるんだ!
ymd65536
1
130
ecspresso, ecschedule, lambroll を PipeCDプラグインとして動かしてみた (プロトタイプ) / Running ecspresso, ecschedule, and lambroll as PipeCD Plugins (prototype)
tkikuc
2
1.9k
PHPで学ぶプログラミングの教訓 / Lessons in Programming Learned through PHP
nrslib
4
1.1k
Swiftコンパイラ超入門+async関数の仕組み
shiz
0
170
ドメインイベント増えすぎ問題
h0r15h0
2
570
Featured
See All Featured
Fashionably flexible responsive web design (full day workshop)
malarkey
406
66k
GraphQLの誤解/rethinking-graphql
sonatard
68
10k
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
33
2k
Building Adaptive Systems
keathley
38
2.4k
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
8
1.2k
How to train your dragon (web standard)
notwaldorf
89
5.8k
Thoughts on Productivity
jonyablonski
68
4.4k
Scaling GitHub
holman
459
140k
Distributed Sagas: A Protocol for Coordinating Microservices
caitiem20
330
21k
The Illustrated Children's Guide to Kubernetes
chrisshort
48
49k
Principles of Awesome APIs and How to Build Them.
keavy
126
17k
How to Think Like a Performance Engineer
csswizardry
22
1.3k
Transcript
JavaScript: The Magic Parts Hannes Moser
–Douglas Crockford If a feature is sometimes useful and sometimes
dangerous and if there is a better option then always use the better option.
–Hannes Moser I am going to use any feature I
am able find within the language!
–Douglas Crockford I made every mistake with JavaScript you could
make.
Libraries
Modules modulecounts.com
npm Modules modulecounts.com
Modules modulecounts.com
npm install pad-left
npm install yolo
npm install swag
choo react, redux & saga lodash yo-yo
∞ Libraries
absurdjs.com
Object Literals
Object Literals const a = 1 const b = 2
const o = { a, b, c() { return 'I am C3PO' } }
Functional Programing
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
Modules
Modules: Export export default { run } export const G
= 9.81
Modules: Import import athlete from 'athlete' import {G} from 'athlete'
const a = athlete.run() / G
Template Strings
Template Strings const foo = 'Hello' const bar = 'World'
console.log(`${foo}, ${bar}!`) // Hello, World!
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)
Destructuring
Destructuring const [a, b] = [1, 2, 3] // a
=== 1, b === 2
Destructuring const {a, b} = {a:1, b:2} // a ===
1, b === 2
Destructuring: Fail-soft const [a, b = 2] = [1] //
a === 1, b === 2
Destructuring: Nesting const {op:a, lhs:{op:b}, rhs:c} = ast()
Defaults
Defaults function trim(str, char = ' ') { … }
trim(' lala land ')
Magic Parts
Named Parameters
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)" })
Named Parameters import assign from 'lodash/assign' function (config) { config
= assign({baseurl: '/'}, config) }
Named Parameters function url({baseurl: '/'}) { … } url({})
Named Parameters function url({baseurl: '/'} = {}){ … } url()
// "/"
Class-free Objects
Class-free Objects: Prototypes function Pokemon(name) { this.name = name //
handle ... } Pokemon.prototype.collect = function() { … } const pikachu = new Pokemon("Pikachu")
Class-free Objects: ES2015 Classes class Pokemon { constructor(name) { this.name
= name // handle ... } collect() { … } } const pikachu = new Pokemon("Pikachu")
Class-free Objects: Constructor Function function pokemon({name} = {}) { function
collect() { … } return { collect } } const pikachu = pokemon({name: 'Pokemon'})
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()
Clean Interfaces
Clean Interfaces export default function pokemon() { function collect() {
… } return {collect} } const pikachu = pokemon() pikachu.bad = function() { … } // no problem at all
Clean Interfaces: Freeze export default function pokemon() { function collect()
{ … } return Object.freeze({collect}) } const pikachu = pokemon() pikachu.bad = function() { … } // throws TypeError or fails silently
Ain't No Party Like a Third-Party JavaScript Party
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' })
Malvertising malware.html
Unicode
Unicode const ಠ_ಠ = "uhu" console.log(ಠ_ಠ) // "uhu"
for-of
for-of const a = [1, 2] for([idx, val] of a.entries())
{ console.log(idx, val) }
mandatory parameters
mandatory parameters function mandatory() { throw new Error("Missing Parameter") }
function foo(a = mandatory()) { … } foo() // Error: Missing Parameter foo(1)
mixins
mixins const Validation = Sup => class extends Sup {
validate(schema) { … } } class Person { … } class Employee extends Validation(Person) { … }
that’s not async
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))
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) }) }) }
async/await const file = await open('hannes.json') const result = process(file)
const html = render(result) console.log(html)
Thank You
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