"js: the right way" by mykyta semenistyi

52
JS: the right way

Upload: binary-studio

Post on 31-Jul-2015

156 views

Category:

Software


0 download

TRANSCRIPT

JS: the right way

JS Frameworks

JS Frameworks

VanillaJS http://vanilla-js.com/

Imperative programming

Variable declaration

Hoisting

Function hoisting

● function declaration body is hoisted ● function expression body is not hoisted

Coercion

1 == true // true

1 === true // false

Coercion

Not readable

Presence check

a = 0

a = null, undefined

Null

ES6 to be fixed

WTF?? Tony Hoare

ALGOL 1965

NaN

ES6

Conditions

Douglas Crockford

NOPE

Conditions

● CYCLOMATIC COMPLEXITY

Defined by Thomas J. McCabe in 1976, this is a count of the number of cycles in the program flow control graph. Effectively the number of distinct paths through a block of code. Lower is better.

● TRUST YOUR CODE

Data types, object consistency etc.

for (var i = 0; i < theArray.length; i++) { copyOfTheArray[i] = theArray[i];}

var len = theArray.length;for (var i = 0; i < len; i++) { copyOfTheArray[i] = theArray[i];}

With caching:

Without caching:

Loops performance

for (var i in theArray) { copyOfTheArray[i] = theArray[i];}

theArray.forEach(function(it, idx){ copyOfTheArray[idx] = it;});

forEach:

for in:

Loops performance

JS performance

“Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at

efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time; premature optimization is the root of all evil. Yet we

should not pass up our opportunities in that critical 3%.”

Donald Knuth, Structured Programming With go to Statements

Object-Oriented Programming

Module

Private members

Please don’t

Prototype methods

method is created in memory 1000000 times

method is created in memory 1 time

var person = { name: "Nicholas", age: 30};

function displayInfo(){ var count = 5; with(person){ alert(name + " is " + age); alert("Count is " + count); }}

displayInfo();

Execution context

Nicholas C. Zakas - Writing Efficient JavaScript: Chapter 7 - Even Faster Websites

Inheritance

Constructor is invoked

Invoke super

Inheritance

Interfaces

Interfaces

Please don’t

Interfaces

API Design Principlesheavily inspired by Ariya Hidayat’s talk https://speakerdeck.com/ariya/javascript-api-design-principles

Boolean trap

Parameter list trap

API Design Principles

Escape from Boolean trap

Escape from Parameter list trap

Event-Driven Development

Event-Driven Developmentproblem

there are usually billions of events

Capo

Functional Programming

Functional JavaScriptfunctions are first-class citizens

JavaScript

Array methods

● forEach● map● reduce● some● every● filter● ...

- compact- hard to debug

Currying

Haskell Brooks Curry

Curryinguse case

someFunction(‘param’);

result

results[‘param’] = result;

return result;

Memoize

return results[‘param’];

someFunction(‘param’);

Util libraries: Standalone modules:

Memoize.js

Memoize

JavaScript Platform

Event loop in JSUI Thread

...onclick XHR state change

setTimeout setInterval

onclick XHR state change

setTimeout

Long running scripts

var sum = 0;for (var i = 0; i < 23000000; i++){

sum += Math.random() * i;}

chunks

by count

by timeif (Date.now() - start > 100){ setTimeout(process, 0);} else { process();}

if (i > 10000){ setTimeout(process, 0);} else { process();}

WebWorkersBring threading to JS

UI Thread:

var worker = new Worker('task.js');worker.addEventListener('message', function(e) { console.log('Worker said: ', e.data);}, false);

worker.postMessage('Hello World');worker.terminate();

Worker:self.addEventListener('message', function(e) { //e.data === ‘Hello World’; //process data self.postMessage(result);}, false);self.close();

var blob = new Blob([ "onmessage = function(e) { postMessage('msg from worker'); }"]);

// Obtain a blob URL reference to our workervar blobURL = window.URL.createObjectURL(blob);

var worker = new Worker(blobURL);

On fly:

Eric Bidelman http://www.html5rocks.com/en/tutorials/workers/basics/

WebWorkersPeculiarities

Workers have access to:● The navigator object● The location object (read-only)● XMLHttpRequest● setTimeout etc.● The Application Cache● Importing external scripts using the importScripts() method● Spawning other web workers

Workers do NOT have access to:

● The DOM (it's not thread-safe)● The window object● The document object● The parent object

Transferrable types:● string● JSON● binary data (File, Blob, ArrayBuffer)

WebWorkersUse cases

Ray TracerVideo/audio

Route Tracer

DNA Analyzing

WebWorkersbut...

You might not need jQueryIE8+

$(‘selector’) document.querySelectorAll(‘selector’)$.ajax new XMLHttpRequest().animate() CSS3 Animations.addClass() .classList.add().html() .innerHTML

...

Text editing

innerHTML innerText textContenthtml parsing layout reflow bingo! IE9+

Pitfalls