JavaScript

Past, Present, Future

http://git.io/UrP6TQ

JavaScript public release

Brendan Eich
 + 
Netscape
 + 

Sun

A complement to Java

for easy online application development


History (1996 - 2006)

1996
Microsoft : JScript
1997
IE4/NN4 : DOM (DHTML)
ECMAScript
1999
IE5 : XMLHttpRequest (AJAX)
ECMAScript3 (~JS 1.5)
Adobe : ActionScript
2001 - 2006
2004

2008 : Google Chrome

Built on V8 JavaScript engine

Browsers war focuses on JavaScript engine speed

2009 : ECMAScript 5

ES5 is mostly a compatibility version (ES4 was abandonned)

2009 : JavaScript out of the browser

NodeJS : to rule them all

  • Based on V8
  • No browser extensions / No (native) DOM
  • Built-in extensions (HTTP, File, Streams, ...)
  • NPM : Node package manager (~54 000 packages)

JavaScript : 3 Key concepts

  • Functional
  • Inheritance
  • this value

Key concepts : Functional language

Functions...

  • Inherit from Object + own executable code
  • Can be wherever an Object can be
  • Can be parameter of other functions
  • Are factory of objects when constructors : new operator
  • Behavior can be adjusted at execution time

Key concepts : inheritance

JavaScript does not use classical inheritance

JavaScript uses Prototype inheritance

You should learn Prototype inheritance

Key concepts : prototype inheritance

  • Gentleman prototyping
    
    function Gentleman(){};
    
    Gentleman.prototype.sayHello = function(){
      console.log("Hello Sir");
    }
    
  • Gentleman instantiating
    
    var gentleman = new Gentleman();
    
    gentleman.sayHello(); // 'Hello Sir'
    
  • Prototype modification
    
    Gentleman.prototype.sayHello = function(){
      console.log("What's up dude ?");
    }
    
  • Modification apply to existing instance
    
    gentleman.sayHello(); // What's up dude ?
    

Key concepts : this value


function foo(){
  console.log(this); // What is `this` ?
} // Looking at this, we can't say.

The value of this in a function

only depends on its invocation mode*

not on its declaration



* There are 4 invocations modes

Key concepts : this value

  • As a function
    foo(); //this === window
  • As a method
    bar.foo(); //this === bar
  • As a constructor
    new foo(); //this === [new built and returned object]
  • With call & apply
    
    	foo.call(baz); //this === baz
    	foo.apply(baz); //this === baz

Exceptions : Function.protoype.bind and Arrow function expressions

Other key concepts

2014 : ECMAScript 6

  • Code name Harmony
  • Target publication date : December 2014
  • Upgrades JS to fit other modern languages
  • Brings new powers to developers



Some features already available

  • ... in some browsers
  • ... in NodeJS : node --harmony

ES6 : New features' pick list

ES6 : Destructuring assignement

Extract data from arrays or objects using a syntax that mirrors
the construction of array and object literals


var a, b;

[a, b] = [1, 2];
// a === 1
// b === 2

[a, b] = [b, a];
// a === 2
// b === 1

[a, ,b] = ["v", "w", "x"];
// a === "v"
// b === "x"

ES6 : Generators

Special functions that generate iterators

yield provoke partial returns

Can be resume with next method


function* greatGenerator(){
  yield "Clermont'ech";
  yield "is great";
  for (var i = 0; i < 3; i++){
    yield i*2;
  }
}

var iterator = greatGenerator();
iterator.next(); // "Clermont'ech"
iterator.next(); // "is great"
iterator.next(); // 0
iterator.next(); // 2

ES6 : Generators

Generators introduce a new expression syntax


//Generator of positive integers iterator
function* posIntGenerator(){
    var value = 0;
    while (true){
        yield value++;
    }
}

var posIntIterator = posIntGenerator();

// New expression syntax below
var posIntBy2Iterator = (anInt * 2 for (anInt in posIntIterator));

posIntBy2Iterator.next(); // 0
posIntBy2Iterator.next(); // 2
posIntBy2Iterator.next(); // 4
posIntBy2Iterator.next(); // 6

ES6 : Arrow functions

Arrow function expressions
are like function expressions
with shorter syntax
+ it binds this value


// This is an anomous function
function(){};

// No parameter, returns undefined
() => {};

// No parameter, returns "foo"
() => "foo"

// Single parameter, returns double
a => a * 2

// Two parameters, returns sum
(a, b) => a + b

					

ES6 : Modules

There was no built-in module concept in JavaScript

...but two standards :


...unfortunately they are not compatible

ES6 introduces another format

Trying to fill the gap

ES6 : Modules

Module definition


// calculator/lib/calc.js
const A_NOT_EXPORTED_CONSTANT = 7;

function multiply(x) {
    return x * A_NOT_EXPORTED_CONSTANT;
}

// Public object exported
module.exports = {
    multiply: multiply
};

Module import


// calculator/main.js
import { multiply } from 'lib/calc';
console.log(multiply(3));

Plus the new <module> tag for the browser

Example from http://www.2ality.com/2013/07/es6-modules.html

Other ES6 features

ES6 : Class

Class keyword but still Prototype inheritance

Sugar syntax to replace framework machinery


class Gentleman extends Dude {
    constructor(name) {
      super(name);
      this.sayHello();
    }

    sayHello() {
      console.log('Hello Sir');
    };
  }
}

ES6 : Spread operators

Expression expands in places
where multiple elements are expected

function sum(a, b, c, d) {
  return a + b + c + d;
}

var expandable = [4, 12, 7, 19];
sum(...expandable); // 42

var expandable2 = [-5, 8];
sum(1, ...expandable2, 20); // 24

var expandable3 = [...expandable, ...expandable2];
//[4, 12, 7, 19, -5, 8]

ES6 : const & let

Brings block scope variables and constantes

if (x) {
  let foo;
  const bar = 10;
  // `foo` and `bar` are defined inside the if block

  bar = 11; // Error
  //the value of `bar` cannot change
}

ES6 : default parameters

You (may) used to write

function f(name, age) {
  age = age || 18;
}

You will write

function f(name, age = 18) {
}

ES6 : Rest parameters

Representation of an indefinite number
of tailing arguments as an array


function sum(a, b, ...args) {
  //args is an Array
  var restSum = args.reduce(function(prev, current){
    return prev + current;
  }, 0);

  return a + b + restSum;
}

sum(1, 2);        // 3
sum(1, 2, 8);     // 11
sum(1, 2, 8, 12); // 23
					

ES6 : Promises

Until now promises were provided by libraries
( jQuery, Q, Bluebird)

Promises are built-in ES6, they :

  • Resolve asynchronous calls concurrency
  • Simplify complex asynchronous code
  • Help to adhere the 1st rule of object calisthenics

ES6 : Proxy

Proxies can change the default behavior
of an object


var proxyTraps = {
  get: function(obj, prop) {
    return 42;
  }
};

var person = new Proxy({ age : 100 }, proxyTraps);
console.log(person.age); // 42
person.age = 18;
console.log(person.age); // 42

The proxyTraps.get is a 'trap' method

There are many others available

Useful for data validation, sanitization, dynamic code analysis...

ES6 : Map & WeakMap

Maps and WeakMaps are key/value maps

Where keys are objects

≠ JS native object : keys are string


var wm = new WeakMap(),
    trivialeObject = {
      'Clermont' : 'Ferrand'
    };

wm.set(trivialeObject, 42);
wm.get(trivialeObject);    // 42
wm.has(trivialeObject);    // true
wm.delete(trivialeObject);
wm.has(trivialeObject);    // false

ES6 : Promises

An example from jQuery with AJAX calls


$.getJSON('customers.json', function(customers){
  $.getJSON('products.json', function(products){
    console.log('We have ' + products.length + ' products');
    console.log('and' + customers.length + ' customers');
  });
});
//Synchronous sequence of async calls : bad pattern
					

var customersPromise = $.getJSON('customers.json'); //Returns a promise
var productsPromise = $.getJSON('products.json'); //Returns another promise

$.when(customersPromise, productsPromise)
 .then(function(customers, products){
    // Called only if both promises are resolved
    console.log('We have ' + products.length + ' products');
    console.log('and' + customers.length + ' customers');
});
					

ES6 is already old story

ES7 is coming next...

Where is JavaScript ?

In your shell with NodeJS,

in your OS with Windows Store App or Node webkit,

in your mobile with PhoneGap, FirefoxOS, Tizen,

in your things with Arduino or BeagleBone,

in the code compiled from C++, Java, C#... via Emcripten,

and in your websites, back and front, with a huge ecosystem.

Cool ! But... where is the doc ?

Mozilla Developer Network

Don't forget to type mdn when Googling

Bad
 
Good

Questions ?

 

@sroucheray


Our community

@ClermontJS on twitter
@ClermontJS