Successfully reported this slideshow.

Hands on: The sexy side of JavaScript (feat. node.js)

1

Share

Loading in …3
×
1 of 41
1 of 41

Hands on: The sexy side of JavaScript (feat. node.js)

1

Share

Download to read offline

Slides of the introductory speech about JavaScript, ES6 and node.js I kept during the second day of the Google I/O Extended 2016 in Catania.

Slides of the introductory speech about JavaScript, ES6 and node.js I kept during the second day of the Google I/O Extended 2016 in Catania.

More Related Content

Related Books

Free with a 14 day trial from Scribd

See all

Related Audiobooks

Free with a 14 day trial from Scribd

See all

Hands on: The sexy side of JavaScript (feat. node.js)

  1. 1. Hands on: The sexy side of JavaScript (feat. node.js) @pirafrankfpira.com Francesco Pira Google #io16 Extended Catania
  2. 2. fpira.com Who I am ? • Web developer • Co-founder @ fileshute.com • VP @ Youth Hub Catania • I like coding, learning new stuff, meet new people (yay!)
  3. 3. Can JavaScript be sexy?
  4. 4. fpira.com ECMAScript, actually… • Official language name • Versions often abbreviated as 'ESx' • ES3 = 1999; • var ES5 = 2015; • const ES6 = 2016; • (ES7 is WIP…)
  5. 5. JavaScript for back-end developers
  6. 6. !==
  7. 7. fpira.com nvm • nvm : node version manager (bash script) • $ nvm install 6.1.0
  8. 8. fpira.com Types • Number (dp 64 bit) • String • Boolean • Object • function, Array, • Date, RegExp • Symbol (ES6+) • NaN • Special objects • undefined • null
  9. 9. fpira.com Truthy and falsy • true • non-zero numbers • "strings" • objects • arrays • functions • false • 0 • "" • undefined • null • NaN
  10. 10. fpira.com Flow control • Conditional statements • Exception handling statements • Promises (since ES6)
  11. 11. fpira.com Conditional statements • if…else • switch if (condition_1) { //statement_1; } else if (condition_2) { //statement_2; } else { //statement_last; } switch (myVar) { case one: //statements break; case two: //statements break; ... default: //statements break; }
  12. 12. fpira.com Loops • while • do…while • for • for…in • for…of for (i==0; i<3; i++) { //statement } var i = 0; do { i += 1; console.log(i); } while (i < 5); while (x < 10) { x++; }
  13. 13. fpira.com for…in vs for…of • for...in iterates over property names • for...of iterates over property values let arr = [3, 5, 7]; arr.foo = "hello"; for (let i in arr) { console.log(i); // logs "0", "1", "2", "foo" } for (let i of arr) { console.log(i); // logs "3", "5", "7" }
  14. 14. fpira.com Exception handling • throw • try…catch • try…catch…finally openMyFile(); try { writeMyFile(theData); } catch(e) { handleError(e); } finally { closeMyFile(); } throw expression;
  15. 15. fpira.com Objects • (almost) everything is an object! var obj = { property1: 'value', property2: 2 }; // OR function Car(make, model) { this.make = make; this.model = model; } var mycar = new Car(“Ford”, “Fiesta");
  16. 16. fpira.com Functions function square(number) { return number * number }; var x = square(5); // x gets the value 25 // OR var square = function(number) { return number * number }; var x = square(4); // x gets the value 16 // OR var factorial = function fac(n) { return n<2 ? 1 : n*fac(n-1) }; console.log(factorial(3)); // logs 6
  17. 17. fpira.com JSON • JS Object Notation • Like 'English' for web apps • "key":value notation • value can be any type (even another object!) { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] }
  18. 18. fpira.com Strict mode • Introduced in ES5 • No subset, it’s different semantics • Dummy errors got illegal • Strict code is faster • Entire script vs. function • ES6 modules are always in strict mode
  19. 19. fpira.com let and const • var , scope is global • let , scope is block (if, loops, switch). • In functions is same as var • const SOME = 4 (can’t be reassigned) • best practise: use it when you require a module ES6
  20. 20. fpira.com Spread operator (…) ES6 // Example 1 function myFunction(x, y, z) { } var args = [0, 1, 2]; myFunction(...args); // arguments are 0,1,2 // Example 2 function myFunction(v, w, x, y, z) { } var args = [0, 1]; myFunction(-1, ...args, 2, ...[3]); // arguments are -1,0,1,2,3 // Example 3 var parts = ['shoulders', 'knees']; var lyrics = ['head', ...parts, 'and', 'toes']; // lyrics is -> ['head', 'shoulders', 'knees', 'and', 'toes']
  21. 21. fpira.com Destructuring • Python-like • Pretty useful • works w/ Objects • works w/ Arrays • Can have defaults • Defaults for functions parameters ES6 var foo = ["x", "y"]; var [one, two] = foo; console.log(one); // "x" console.log(two); // "y" [a, b, ...rest] = [1, 2, 3, 4, 5] console.log(a) // 1 console.log(b) // 2 console.log(rest) // [3, 4, 5] ({a, b} = {a:1, b:2}) console.log(a) // 1 console.log(b) // 2 var o = {p: 42, q: true}; var {p, q} = o; console.log(p); // 42 console.log(q); // true
  22. 22. fpira.com Classes • Syntax sugar for specific kind of function • Support for properties and inheritance • No private methods (you need to fake them!) • We can pass a class as parameter ES6
  23. 23. fpira.com Classes: ES5 vs ES6 // ES6 class Shape { constructor (id, x, y) { this.id = id this.move(x, y) } move (x, y) { this.x = x this.y = y } } // ES5 var Shape = function (id, x, y) { this.id = id; this.move(x, y); }; Shape.prototype.move = function (x, y) { this.x = x; this.y = y; }; ES6
  24. 24. fpira.com Arrow functions • More concise syntax • this has same scope of parent • no arguments, use spread operator (…args) • use ({}) for empty objects function (a, b) { return a * b; } (a, b) => a * b var that = this; var helper = function () { that.num = add(that.num, that.num); }; function () { return arguments[0]; } (...args) => args[0] () => {} // undefined () => ({}) // {} ES6
  25. 25. fpira.com …there’s more! • Symbols • Iterators and Generators • new Array methods • Map, Set • functional programming in JS ES6
  26. 26. node.js for back-end developers
  27. 27. fpira.com What’s node.js? • Event-driven JavaScript runtime • Built on top of V8 (Chromium JS engine) • Core in C++ • Rest of it in JavaScript • v6.x covers 93% of ES6 (http://kangax.github.io/compat-table/es6/) • "Designed to build scalable web applications"
  28. 28. fpira.com Why node.js? • Event driven • Async I/O • Non-blocking calls • Single-threaded • Thousands of concurrent connections • Great in cluster environment
  29. 29. fpira.com npm • npm : node package manager • $ npm install -g gulp • $ npm … • init • install • start • test • etc.
  30. 30. fpira.com App structure • package.json • node_modules • test • src/app • …
  31. 31. fpira.com Import and Export "use strict"; var xorshift = require('xorshift'); function uniformint(a, b) { return Math.floor(a + xorshift.random() * (b - a)); } console.log(uniformint(100100, 990900)); module.exports = { generateCode: function (){ return uniformint(100100, 990900); } } var myModule = require('./genCode');
  32. 32. fpira.com Coding style • Curly braces go in same line • Don’t use curly braces if not needed! • 99.98% no need to use semicolons • Multiple line list? Comma first • Single quotes are better • white space before ( • use named functions • callback last argument, err its first argument • UpperCamelCase for class names • lower-and-hyphed for config keys • CAPS_SNAKE_CASE for constants • lowerCamelCase for all the rest • Init to true, false, null or 0 responsibly • undefined means 'no set yet' • new Error obj w/ your message • Make logs, save lives
  33. 33. fpira.com Non-blocking code var data = file.readFileSync('file.txt'); console.log(data); console.log('Hello'); // These lines log data and then 'Hello' // VS file.readFile('file.txt', function(err, data) { console.log(data); }); console.log('Hello'); // These lines log 'Hello' and then data
  34. 34. fpira.com Promises • For deferred and async operations • 4 states: • pending: initial state, not fulfilled or rejected. • fulfilled: successful operation • rejected: failed operation. • settled: the Promise is either fulfilled or rejected, but not pending. • Piramide of doom! => to be improved… (ES7?) ES6
  35. 35. fpira.com Promises ES6
  36. 36. fpira.com A dummy webserver const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello Worldn'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
  37. 37. fpira.com • JavaScript: The Good Parts • MDN • node.js doc • yourModuleOfChoice doc Notes - not all courses are good - no good doc, no good module Resources
  38. 38. fpira.com Next • Read the doc! • Explore Symbol, Map, Set, Iterators and Generators • Write your first node.js project • Try the Express web framework • Understand Express middleware • Get to know JS testing (Mocha and Jasmine)
  39. 39. fpira.com Next (more) • Gulp • Babel • TypeScript • Read about JS functional programming • (https://medium.com/@chetcorcos/functional-programming-for-javascript- people-1915d8775504#.bawhglud6)
  40. 40. Thank you! Questions? @pirafrankfpira.com Francesco Pira

×