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
69
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
fs2-io を試してたらバグを見つけて直した話
chencmd
0
220
今年のアップデートで振り返るCDKセキュリティのシフトレフト/2024-cdk-security-shift-left
tomoki10
0
190
talk-with-local-llm-with-web-streams-api
kbaba1001
0
170
The rollercoaster of releasing an Android, iOS, and macOS app with Kotlin Multiplatform | droidcon Italy
prof18
0
150
Criando Commits Incríveis no Git
marcelgsantos
2
170
CSC509 Lecture 14
javiergs
PRO
0
130
ゆるやかにgolangci-lintのルールを強くする / Kyoto.go #56
utgwkk
1
360
Refactor your code - refactor yourself
xosofox
1
260
ブラウザ単体でmp4書き出すまで - muddy-web - 2024-12
yue4u
2
460
コンテナをたくさん詰め込んだシステムとランタイムの変化
makihiro
1
120
useSyncExternalStoreを使いまくる
ssssota
6
1k
Fibonacci Function Gallery - Part 1
philipschwarz
PRO
0
210
Featured
See All Featured
Product Roadmaps are Hard
iamctodd
PRO
49
11k
A Tale of Four Properties
chriscoyier
157
23k
Making Projects Easy
brettharned
116
5.9k
個人開発の失敗を避けるイケてる考え方 / tips for indie hackers
panda_program
95
17k
Learning to Love Humans: Emotional Interface Design
aarron
273
40k
Keith and Marios Guide to Fast Websites
keithpitt
410
22k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
10
810
Imperfection Machines: The Place of Print at Facebook
scottboms
266
13k
10 Git Anti Patterns You Should be Aware of
lemiorhan
PRO
656
59k
Unsuck your backbone
ammeep
669
57k
Scaling GitHub
holman
458
140k
Adopting Sorbet at Scale
ufuk
73
9.1k
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