JavaScript in 2016 – Current status of JS development – Javascript



JavaScript in 2016 – Current status of JS development – Javascript

0 2


lightning-talk-js-2016

Lightning Talk - State of JavaScript programming

On Github purplecode / lightning-talk-js-2016

JavaScript in 2016

Current status of JS development

Javascript

This is Javascript. If you put big wheels and a racing stripe on a golf cart, it's still a fucking golf cart.

@source: if programming languages were vehicles

WAT

2 == [2];
// true

2 == [[2]];
// true

[] + [];
// ""

[] + {};
// "[object Object]"

{} + [];
// 0

WAT

"string" instanceof String;
// false

String("abc") instanceof String;
// false

new String("abc") instanceof String;
// true

111111111111111111111 === 111111111111111110000;
 // true
Recommended:  A lightning talk by Gary Bernhardt [CodeMash, 2012]

Popularity

Popularity

languages usage

@source: github

Popularity

libraries count

@source:  www.modulecounts.com

Popularity

stackoverflow questions & answers

@source:  https://smthngsmwhr.wordpress.com

Popularity

twitter mentioning

@source:  http://blog.revolutionanalytics.com

Popularity

most in-demand languages in 2016

@source:  www.codingdojo.com

Popularity

google trends - tutorials search

@source:  pypl.github.io

Ubiquity

Ubiquity

Browser & server

  • Node.js
  • Angular
  • React
  • Ember
  • Backbone
  • Meteor
  • Polymer
  • Aurelia
  • ...

Ubiquity

Cross platform desktop apps

Ubiquity

Mobile native apps

Ubiquity

Microcontrollers

Ubiquity

Drones & IoT

Ubiquity

Shell

Ubiquity

Virtualisation

V86

ECMAScript

Version Date published 1.0 1997 2.0 1998 3.0 1999 4.0 abandoned 5.0 2009 5.1 2011 6.0 2015 7.0 in progress * JavaScript/Mocha/LiveScript - 1995, Brendan Eich, Netscape

ES6 - Classes

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

let p = new P(100, 200);

ES6 - let, const, var

function() {
    if(true) {
        var v = 1;
        let l = 1;
        const c = 1;
    }
    console.log(v, l, c);
}

ES6 - spread & destructuring

let array = [1, 2, 3, 4, 5];

let [one, two, ...rest] = array; // one = 1, two = 2, rest = [3, 4, 5]

let array2 = [...array, 6, 7, 8] // [1, 2, 3, 4, 5, 6, 7, 8]
let {a, b} = {a:1, b:2} // a = 1, b = 2

let {a, b, ...rest} = {a:1, b:2, c:3, d:4}  // ES7

let [a, b] = [b, a]; // swap

ES6 - spread & destructuring

let obj = {a:1, b:2};

let d = 4;

let obj2 = {
    ...obj,
    c:3,
    d
}
// obj2 = {"a":1, "b":2, "c":3, "d":4}

ES6 - destructuring

function f({a, b}) {
    return a + b;
}

f({a: 1, b: 2})
function plot({size = 10, cords = { x: 0, y: 0} } = {}) {
    ...
}

plot({ cords: { x: 18, y: 30 } });

ES6 - modules

export const PI = Math.PI;
export function sin(x) {}
export function cos(x) {}
export function random(x) {}

export default {
    PI,
    sin,
    cos,
    random
}
import { PI } from 'my/module';
import { sin, cos } from 'my/module';
import { random as mathRandom } from 'my/module';

import Math from 'my/module';

ES6 - string templates

let x = 2, y = 3;

let text = `value of x = ${x + y}`
`
    multi
    line
`

ES6 - tagged template literals

function tag(strings, ...values) {
  return function(obj) {
        return strings[0] + obj[values[0]] + strings[1];
  };
}

let hello = tag`Hello ${'name'}!`;

hello({name: 'Alice'});     // "Hello Alice!"
hello({name: 'Bob'});       // "Hello Bob!"

ES6 - generators

function* oneTwo(){
    yield 1;
    yield 2;
}

let gen = oneTwo();

console.log(gen.next()); // {value: 1, done: false}
console.log(gen.next()); // {value: 1, done: false}
console.log(gen.next()); // {value: undefined, done: true}

ES6 - rest arguments

function argsLength(...theArgs) {
    console.log(theArgs.length);
}

argsLength();           // 0
argsLength(5);          // 1
argsLength(5, 6, 7);    // 3

ES6 - arrow functions

function (a) {
    return a * 2;
}

a => a * 2

() => 4

(a, b) => a * b

(a, b) => {
    return a * b;
}
return function() {
    return this.text
}.bind(this);

return () => this.text

ES6 - promises

let promise = new Promise((resolve, reject) => {
    let result = Math.random();
    result < 0.5 ? resolve(result) : reject('too much');
});

promise
    .then(result => console.log(result))
    .catch(e => console.log(`error: ${e}`))

ES6 - more...

  • Map, Set
  • WeakMap, WeakSet
  • Reflect
  • Symbol
  • Proxy

ES7- more, more, more...

Exponentiation operator

let cubed = x => x ** 3;

async/await

async function asyncFunction() {
  await functionReturningPromise();
}
asyncFunction().then(...)

decorators

class Person {
  @memoized
  get name() { return 'Bob'; }
}

class properties

class Person {
    name = 'Alice';
    static says = 'I love JS!';
}

Tooling

NPM & Bower

package managers for JavaScript

Gulp & Grunt

JavaScript build system and task runner

Webpack

module bundler for JavaScript

Firebug & Chrome Dev Tools

JavaScript debugging tools

Babel

pluggable JavaScript compiler

Evolution

Transpilers

source-to-source compilers

  • CoffeeScript - syntactic sugar inspired by Ruby, Python and Haskell
  • TypeScript - superset of JavaScript with optional static typing
  • Dart - general-purpose programming language developed by Google
  • JSX - superset with XML-like syntax for HTML elements representation

Other (366): ruby (9), python (16), java (16), scala (4), .NET (19), lisp-like (23)

@more:  Languages compiled to JavaScript

Typescript

interface Shape {
    new (color: string);
}

class Square implements Shape  {
    private size: number;
    constructor(size: number, color: string) {
        super(color);
        this.size = size;
    }
}

var square: Square = new Square(10, 'blue');

Typescript

declare namespace d3 {
    export var version: string;
    export function select(selector: string): Selection;
    export function selectAll(nodes: EventTarget[]): Selection;
}

declare module 'd3' {
    export = d3;
}

Asm.js

Strict subset JavaScript for significant performance improvements of applications that are written in statically-typed languages. ~2x slower than native compilation of C with clang.

size_t strlen(char *ptr) {
  char *curr = ptr;
  while (*curr != 0) {
    curr++;
  }
  return (curr − ptr);
}


function strlen(ptr) {
  ptr = ptr|0;
  var curr = 0;
  curr = ptr;
  while (MEM8[curr]|0 != 0) {
    curr = (curr + 1)|0;
  }
  return (curr − ptr)|0;
}
@source:  Wikipedia

Benchmark

@source:  http://kukun.in/asm-js-speed-benchmark

Good to know

Web Workers

JavaScript threads running in the background

index.js
var worker = new Worker("workerScript.js"); worker.postMessage({id: 0, text : '...'}); worker.onmessage(event => console.log(event.data));
workerScript.js
onmessage = (event) => { postMessage({ id: event.data.id, result: eval(event.data.data) }); }

Virtual DOM

  • DOM is not optimal for dynamic UI
  • mimic DOM in JavaScript and apply only diff
  • minimum number of operations to transform one tree into another ~ O(n3)
  • React.js - non-optimal heuristic ~ O(n) (unique keys, model assumptions)
  • implementations: React, Mithril, Matt-Esch/virtual-dom

Shadow DOM

<template id="template">
    <style>
        ...
    </style>
    <div class="outer">
        <div class="title">Hello world from</div>
        <div class="name">
            <content></content>
        </div>
    </div>
</template>
<div id="example"></div>
<script>
    var shadow = document.querySelector('#example').createShadowRoot();
    var template = document.querySelector('#template');
    var clone = document.importNode(template.content, true);
    shadow.appendChild(clone);
</script>
Hello world from
Shadom DOM

IndexedDB

  • client-side storage for structured data, files or blobs
  • asynchronous, transactional, indexes
  • same-origin principle, available from web-workers
  • wrapper: dexie
var request = window.indexedDB.open("hollywood", 1);
request.onerror = event => console.log("Error", event);
request.onupgradeneeded = (event) => {
    var database = event.target.result;
    database.createObjectStore("movies", {keyPath: "id"})
        .add({ id: "0", name: "Seksmisja" });
}
request.onsuccess = event => {
    var database = event.target.result;
    var transaction = database.transaction(["movies"], "readonly")
        .objectStore("movies")
        .get("0");
    transaction.onsuccess = event => console.log(transaction.result);
    transaction.onerror = event => console.log("Error", event);
};

Sockets

  • full-duplex communication channels over a single TCP connection
var socket = new WebSocket('ws://domain.com:12010/api');
socket.onopen = () => {
  setInterval(function() {
      socket.send(data);
  }, 100);
};
socket.onmessage = (event) => {
    console.log(event.data);
}

Server push

  • transaction is initiated by the server
var indexFile = fs.readFileSync(path.join(__dirname, './index.js'));
var addons = path.join(__dirname, '/addons.js');

function onRequest(request, response) {
   var filename = path.join(__dirname, request.url);
     if (response.push) {
       var push = response.push('/addons.js');
       push.writeHead(200);
       fs.createReadStream(addons).pipe(push);
     }
     response.end(indexFile);
 }

http2.createServer(options, onRequest).listen(8080);

Server side rendering

  • page loads faster, no white page
  • content is visible to search engine
  • less browser compatibility issues
  • doable current frameworks like React
var React = require('react');
var ReactDOM = require('react-dom');

class MyComponent extends React.Component {
    render() {
        return <div>Hello World</div>;
    }
}
ReactDOM.render(<MyComponent />, node);
var React = require('react');
var ReactDOMServer = require('react-dom/server');

class MyComponent extends React.Component {
    render() {
        return <div>Hello World</div>;
    }
}
ReactDOMServer.renderToString(<MyComponent />);

This is all for now...

Thanks!