Date post: | 21-Jan-2017 |
Category: |
Presentations & Public Speaking |
Upload: | igor-laborie |
View: | 347 times |
Download: | 0 times |
JS is now a major programming language
http://www.sitepoint.com/whats-best-programming-language-learn-2015/
http://redmonk.com/sogrady/2015/07/01/language-rankings-6-15/
Once Upon the time• 1995: created by Brendan Eich
• 1997: Standard ECMA-262
• 2004: Firefox
• 2008: Chrome with V8
• 2009: ES5, NodeJS
• 2015: ES6 ES2015
• 2016: (ES7) ES2016
No longer problems• Browser fragmentation
OK with IE9+ http://kangax.github.io/compat-table/es5/
• DebuggingChrome, Firefox, …
• Editorshttps://atom.io/http://www.sublimetext.com/https://www.jetbrains.com/webstorm/
…
Simplehttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
• boolean, null, undefined
• number (IEEE 754 double-precision binary floating-point format)
• string
• object
• function
JSON• Native JavaScript format
• Easier than XML to express data
• Easier to read for mankind
• Easier to read for computer
• Native JavaScript API:JSON.parse, JSON.format
Functional
• Functions are first class citizen
• Closure
• Easy to handle function (currying, memoization)
• <!> with the callback hell*
Type coercion
• some time useful (default param, check is valid)
• Very dangerous:+ not symmetric == not transitive
Function Arguments
• https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
• Useful for varargs
• Use default param pattern*
Type coercion// + not symmetricconsole.log([] + []); // '' empty Stringconsole.log([] + {}); // '[object Object]' toString on an empty objectconsole.log({} + []); // 0 the numberconsole.log({} + {}); // NaN the number// == not transitive console.log("0" == 0); // trueconsole.log(0 == ""); // trueconsole.log("0" == ""); // false
Function Argumentsvar fun; // Classic callfun = function (a, b) { return {a: a, b: b}; }; console.log('fun(1, 2)', fun(1, 2)); // { a: 1, b: 2 }console.log('fun(1)', fun(1)); // { a: 1, b: undefined }console.log('fun(1, 2, 3)', fun(1, 2, 3)); // { a: 1, b: 2 }// Using the argumentsfun = function () { var a = arguments[0]; var b = arguments[1]; // can be converted to Array with Array.prototype.slice.call(arguments) return {a: a, b: b}; }; console.log('fun(1, 2)', fun(1, 2)); // { a: 1, b: 2 }console.log('fun(1)', fun(1)); // { a: 1, b: undefined }console.log('fun(1, 2, 3)', fun(1, 2, 3));
What is this ?
• The instance object ?
• null or undefined ?
• The element that trigger the event ?
• Anything you want:fun.apply(thisArg, [arg1, arg2, ...])fun.call(thisArg, arg1, arg2, ...)
Scope & hoisting
• <!> with global scope
• var scope is function*
• Hoisting is unnatural, use with care, for anonymous function only
Summary
• WARN with dangerous JavaScript featuresby default set
• Learn the language: JavaScript the good part
• Lint your code: http://eslint.org/
"use strict";
What is NodeJS• Java has JVM - JavaScript has NodeJS
based on V8with low level API
• Handled by the Node.js Foundation
• Isomorphic JavaScript
• There are alternatives JavaScript engine for server side (e.g. Nashorn since Java 8)
Hello World
// arg0: node// arg1: js file// arg1: paramvar name = process.argv[2] || 'World'; console.log('Hello', name, '!');
Require & Export// Expose an object with version and plopmodule.exports = { version: '1.0.0', plop: function (name) { console.log('Plop', name || '', '!'); } };
// import the local exportAPI filevar api = require('./exportAPI'); console.log('API version', api.version); api.plop('toto');
Minimal HTTP server// import standard http module provided by nodevar http = require('http'); // Create a server with a callback handlervar server = http.createServer(function (request, response) { console.log(request.method, request.url); // show request // write status and a header response.writeHead(200, {'Content-Type': 'text/plain'}); // write body response.end('Hello World !\n'); }); // open server on the specific portserver.listen(8000); console.log('Server open on http://localhost:8000');
Node ecosystem: npm• Auto installed with NodeJS
• https://www.npmjs.com/
• package.json to define project informationnpm init to initialize your project
• Add a dependency in your projectnpm install --save <dependency>[@version]
• Install a global utility npm install -g <utility>
<3 proxy
npm config set proxy "http://<user>:<password>@proxy2.akka.eu:9090" npm config set https-proxy "http://<user>:<password>@proxy2.akka.eu:9090"
• Set the HTTP_PROXY and HTTPS_PROXY
Moments.js
// import monentvar moment = require('moment'); // get XMas date (http://momentjs.com/)var xmas = moment('25-12-2015', 'dd-MM-YYYY'); // Display relative date to nowconsole.log(xmas.toNow());
Expressvar express = require('express'); // import expressvar app = express(); // create application// define default routeapp.get('/', function (request, response) { console.log(request.method, request.url); // show request response.status(200).send('Hello World !'); // send OK with message}); // start the servervar server = app.listen(8000, function () { // called when server is started console.log('Started at http://localhost:%s', server.address().port); });
Tools using NodeJS• Modern web build tools
Gulp, Grunt, …
• Languages tools ESLint, JSHint, JSLint, …lessc, BabelJS, TypeScript, …
• Testing frameworks Karma, Protractor, Mocha, …
• Others: http-server
ES6 ES2015
• JavaScript engine support: https://kangax.github.io/compat-table/es6/
• Evergreen browser (including Microsoft Edge) have a good support
• We can use a transpiler like BabelJShttps://babeljs.io/docs/learn-es2015/
Features• String templates
• Let & const
• Lambda syntax
• Class
• Promises
• Object literals
• Modules
• Iterable, for ..of
• Generators
• Destructuring
• Default, rest, spread
• Proxy, Map, Set, …
• …
Code
• String templates
• Let & const
• Lambda syntax
• Class & object literals
• Default params
• Promises
String templates
var name = process.argv[2] || 'World'; // console.log('Hello ' + name + '!');console.log(`Hello ${name}!`);
Let & const
// With var !var doSomething = function (a) { var res = 0; if (a) { var res = 'a'; } res++; return res; };
Let & const
// With let ! let doSomething = function (a) { let res = 0; if (a) { let res = 'a'; } res++; return res; };
Let & const
// With constconst doSomething = function (a) { const res = 0; if (a) { res = 'a'; // fail here } res++; // fail here return res; };
Lambda
//var aux = function (n, acc) {// return (n < 2) ? acc : aux(n - 1, n * acc);//};var aux = (n, acc) => (n < 2) ? acc : aux(n - 1, n * acc);
Class & Object literals// Define the Animal classclass Animal { constructor(name) { this.name = name; } talk() { console.log(`My name is ${this.name}`); } } const rex = new Animal('Rex'); rex.talk(); // My name is Rex
Class & Object literals
// Define the Cat classclass Cat extends Animal { talk() { console.log(`MEOW, my name is ${this.name}`); } } const osiris = new Cat('Osiris'); osiris.talk(); // MEOW, my name is Osiris
Default parameter
//var aux = (n, acc) => {// const value = acc || 1;// return (n < 2) ? value : aux(n - 1, n * value);//}var aux = (n, acc = 1) => { return (n < 2) ? acc: aux(n - 1, n * acc); };
PromisesMongoClient.connect(config.url) .then(db => log.info(`Connected correctly to ${config.url}`) || db) .then(db => log.info(`Create DB ...`) || db) .then(db => createDB(db, extract)) .then(db => log.info(`Compute points ...`) || db) .then(db => computePoints(db)) .then(db => log.info(`Compute ranks ...`) || db) .then(db => ranks(db)) .then(db => log.info(`Compute classements ...`) || db) .then(db => classements(db)) .then(db => db.close()) .then(() => log.info('done')) .catch(err => log.error(err));
Learn ES2015
• https://babeljs.io/docs/learn-es2015/
• http://www.smashingmagazine.com/2015/10/es6-whats-new-next-version-javascript/
• https://hacks.mozilla.org/category/es6-in-depth/
JavaScript can be good• Do not underestimate JavaScript
• Learn it, use ittry ES2015 with BabelJS or NodeJS 4+
• https://developer.mozilla.org/en-US/docs/Web/JavaScript
• codeschool, codeacademy, lynda, openclassrooms, …
• ‘JavaScript the good part’‘Secrets of the JavaScript Ninja’
Alternatives• TypeScript: http://www.typescriptlang.org/
~ ES2015 with types
• CoffeeScript: http://coffeescript.org/~ES2015 with ~pythonish syntax
• Elm: http://elm-lang.org/more functional
• Modern language compile to JS: Scala.js, Ceylon.js, go, …