41
Hands on: The sexy side of JavaScript (feat. node.js) @pirafrank fpira.com Francesco Pira Google #io16 Extended Catania

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

Embed Size (px)

Citation preview

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

Hands on:

The sexy side of JavaScript (feat. node.js)

@pirafrankfpira.com Francesco Pira

Google #io16 Extended Catania

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

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!)

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

Can JavaScript be sexy?

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

fpira.com

ECMAScript, actually…

• Official language name

• Versions often abbreviated as 'ESx'

• ES3 = 1999;

• var ES5 = 2015;

• const ES6 = 2016;

• (ES7 is WIP…)

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

JavaScript for back-end developers

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

!==

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

fpira.com

nvm

• nvm : node version manager (bash script)

• $ nvm install 6.1.0

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

fpira.com

Types

• Number (dp 64 bit)

• String

• Boolean

• Object

• function, Array,

• Date, RegExp

• Symbol (ES6+)

• NaN

• Special objects

• undefined

• null

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

fpira.com

Truthy and falsy

• true

• non-zero numbers

• "strings"

• objects

• arrays

• functions

• false

• 0

• ""

• undefined

• null

• NaN

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

fpira.com

Flow control

• Conditional statements

• Exception handling statements

• Promises (since ES6)

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

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; }

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

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++; }

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

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" }

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

fpira.com

Exception handling

• throw

• try…catch

• try…catch…finally

openMyFile(); try { writeMyFile(theData); } catch(e) { handleError(e); } finally { closeMyFile(); }

throw expression;

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

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");

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

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

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

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" } ]}

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

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

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

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

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

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']

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

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

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

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

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

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

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

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

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

fpira.com

…there’s more!

• Symbols

• Iterators and Generators

• new Array methods

• Map, Set

• functional programming in JS

ES6

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

node.js for back-end developers

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

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"

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

fpira.com

Why node.js?

• Event driven

• Async I/O

• Non-blocking calls

• Single-threaded

• Thousands of concurrent connections

• Great in cluster environment

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

fpira.com

npm

• npm : node package manager

• $ npm install -g gulp

• $ npm …

• init

• install

• start

• test

• etc.

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

fpira.com

App structure

• package.json

• node_modules

• test

• src/app

• …

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

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');

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

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

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

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

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

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

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

fpira.com

Promises

ES6

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

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 World\n'); });

server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });

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

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

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

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)

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

fpira.com

Next (more)

• Gulp

• Babel

• TypeScript

• Read about JS functional programming

• (https://medium.com/@chetcorcos/functional-programming-for-javascript-people-1915d8775504#.bawhglud6)

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

Thank you!

Questions?

@pirafrankfpira.com Francesco Pira