SlideShare a Scribd company logo
Hands on:
The sexy side of JavaScript
(feat. node.js)
@pirafrankfpira.com Francesco Pira
Google #io16 Extended Catania
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!)
Can JavaScript be sexy?
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…)
JavaScript
for back-end developers
!==
fpira.com
nvm
• nvm : node version manager (bash script)
• $ nvm install 6.1.0
fpira.com
Types
• Number (dp 64 bit)
• String
• Boolean
• Object
• function, Array,
• Date, RegExp
• Symbol (ES6+)
• NaN
• Special objects
• undefined
• null
fpira.com
Truthy and falsy
• true
• non-zero numbers
• "strings"
• objects
• arrays
• functions
• false
• 0
• ""
• undefined
• null
• NaN
fpira.com
Flow control
• Conditional statements
• Exception handling statements
• Promises (since ES6)
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;
}
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++;
}
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"
}
fpira.com
Exception handling
• throw
• try…catch
• try…catch…finally
openMyFile();
try {
writeMyFile(theData);
} catch(e) {
handleError(e);
} finally {
closeMyFile();
}
throw expression;
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");
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
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"
}
]
}
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
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
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']
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
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
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
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
fpira.com
…there’s more!
• Symbols
• Iterators and Generators
• new Array methods
• Map, Set
• functional programming in JS
ES6
node.js
for back-end developers
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"
fpira.com
Why node.js?
• Event driven
• Async I/O
• Non-blocking calls
• Single-threaded
• Thousands of
concurrent connections
• Great in cluster
environment
fpira.com
npm
• npm : node package manager
• $ npm install -g gulp
• $ npm …
• init
• install
• start
• test
• etc.
fpira.com
App structure
• package.json
• node_modules
• test
• src/app
• …
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');
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
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
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
fpira.com
Promises
ES6
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}/`);
});
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
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)
fpira.com
Next (more)
• Gulp
• Babel
• TypeScript
• Read about JS functional programming
• (https://medium.com/@chetcorcos/functional-programming-for-javascript-
people-1915d8775504#.bawhglud6)
Thank you!
Questions?
@pirafrankfpira.com Francesco Pira

More Related Content

What's hot

Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
Tomer Gabel
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
Alfonso Ruzafa
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
Doris Chen
 
Scala Types of Types @ Lambda Days
Scala Types of Types @ Lambda DaysScala Types of Types @ Lambda Days
Scala Types of Types @ Lambda Days
Konrad Malawski
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functional
djspiewak
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1
Hackraft
 
Денис Лебедев, Swift
Денис Лебедев, SwiftДенис Лебедев, Swift
Денис Лебедев, Swift
Yandex
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf42
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
John De Goes
 
Scala In The Wild
Scala In The WildScala In The Wild
Scala In The Wild
djspiewak
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
Kazunobu Tasaka
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
Kazunobu Tasaka
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
David Muñoz Díaz
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
Eduard Tomàs
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
Francesco Usai
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
Michael Galpin
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?
Sarah Mount
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
Jimin Hsieh
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
SacalaZa #1
SacalaZa #1SacalaZa #1
SacalaZa #1
Hiroki Mizuno
 

What's hot (20)

Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...OSCON Presentation: Developing High Performance Websites and Modern Apps with...
OSCON Presentation: Developing High Performance Websites and Modern Apps with...
 
Scala Types of Types @ Lambda Days
Scala Types of Types @ Lambda DaysScala Types of Types @ Lambda Days
Scala Types of Types @ Lambda Days
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functional
 
Swift rocks! #1
Swift rocks! #1Swift rocks! #1
Swift rocks! #1
 
Денис Лебедев, Swift
Денис Лебедев, SwiftДенис Лебедев, Swift
Денис Лебедев, Swift
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
Scala In The Wild
Scala In The WildScala In The Wild
Scala In The Wild
 
Working with Cocoa and Objective-C
Working with Cocoa and Objective-CWorking with Cocoa and Objective-C
Working with Cocoa and Objective-C
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 
T3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmerT3chFest 2016 - The polyglot programmer
T3chFest 2016 - The polyglot programmer
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
Scala in Practice
Scala in PracticeScala in Practice
Scala in Practice
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
Scala - just good for Java shops?
Scala - just good for Java shops?Scala - just good for Java shops?
Scala - just good for Java shops?
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
SacalaZa #1
SacalaZa #1SacalaZa #1
SacalaZa #1
 

Viewers also liked

Writing jQuery that doesn't suck - London jQuery
Writing jQuery that doesn't suck - London jQueryWriting jQuery that doesn't suck - London jQuery
Writing jQuery that doesn't suck - London jQuery
Ross Bruniges
 
The Potato Story 一袋土豆
The Potato Story 一袋土豆The Potato Story 一袋土豆
The Potato Story 一袋土豆
Joe Carter
 
Sovereignty, Free Will, and Salvation - Limited Atonement
Sovereignty, Free Will, and Salvation - Limited AtonementSovereignty, Free Will, and Salvation - Limited Atonement
Sovereignty, Free Will, and Salvation - Limited Atonement
Robin Schumacher
 
Eating and exercise habits of the students in our school
Eating and exercise habits of the students in our schoolEating and exercise habits of the students in our school
Eating and exercise habits of the students in our school
nikseis
 
All about Interview
All about InterviewAll about Interview
All about Interview
Pratik Patel
 
Cultural diversity and unlocking the human potential
Cultural diversity and unlocking the human potentialCultural diversity and unlocking the human potential
Cultural diversity and unlocking the human potential
pitra.hutomo
 
Newton's laws jeopardy
Newton's laws jeopardyNewton's laws jeopardy
Newton's laws jeopardy
rlinde
 
ChinaUnix社区介绍
ChinaUnix社区介绍ChinaUnix社区介绍
ChinaUnix社区介绍
send_linux
 
SIGEVOlution Spring 2007
SIGEVOlution Spring 2007SIGEVOlution Spring 2007
SIGEVOlution Spring 2007
Pier Luca Lanzi
 
Cilmatic Risk Assessment Of Southern Express Way in Sri Lanka
Cilmatic Risk Assessment Of Southern Express Way in Sri LankaCilmatic Risk Assessment Of Southern Express Way in Sri Lanka
Cilmatic Risk Assessment Of Southern Express Way in Sri Lanka
Maersk Line
 
关于 Twitter 以及 Twitter 与 NGO2.0
关于 Twitter 以及 Twitter 与 NGO2.0关于 Twitter 以及 Twitter 与 NGO2.0
关于 Twitter 以及 Twitter 与 NGO2.0
刘 勇
 
2011 expoward primaria 6to. año c2
2011 expoward primaria 6to. año c22011 expoward primaria 6to. año c2
2011 expoward primaria 6to. año c2
nm48
 
Randall Santos - Portfolio 2008
Randall Santos - Portfolio 2008Randall Santos - Portfolio 2008
Randall Santos - Portfolio 2008
randallsan
 
4-31 NTC Information Sheet SEP 2012
4-31 NTC Information Sheet SEP 20124-31 NTC Information Sheet SEP 2012
4-31 NTC Information Sheet SEP 2012
Tracey Jones
 
Jeffrey Sachs
Jeffrey SachsJeffrey Sachs
Jeffrey Sachs
rosiem7
 
Poster the physiological effects of obesity on body system latest
Poster the physiological effects of obesity on body system latestPoster the physiological effects of obesity on body system latest
Poster the physiological effects of obesity on body system latest
nur fara
 
DMI Light Towers - Operational Manual
DMI Light Towers - Operational ManualDMI Light Towers - Operational Manual
DMI Light Towers - Operational Manual
scottf11
 

Viewers also liked (18)

Writing jQuery that doesn't suck - London jQuery
Writing jQuery that doesn't suck - London jQueryWriting jQuery that doesn't suck - London jQuery
Writing jQuery that doesn't suck - London jQuery
 
The Potato Story 一袋土豆
The Potato Story 一袋土豆The Potato Story 一袋土豆
The Potato Story 一袋土豆
 
Sovereignty, Free Will, and Salvation - Limited Atonement
Sovereignty, Free Will, and Salvation - Limited AtonementSovereignty, Free Will, and Salvation - Limited Atonement
Sovereignty, Free Will, and Salvation - Limited Atonement
 
Eating and exercise habits of the students in our school
Eating and exercise habits of the students in our schoolEating and exercise habits of the students in our school
Eating and exercise habits of the students in our school
 
All about Interview
All about InterviewAll about Interview
All about Interview
 
Cultural diversity and unlocking the human potential
Cultural diversity and unlocking the human potentialCultural diversity and unlocking the human potential
Cultural diversity and unlocking the human potential
 
Newton's laws jeopardy
Newton's laws jeopardyNewton's laws jeopardy
Newton's laws jeopardy
 
ChinaUnix社区介绍
ChinaUnix社区介绍ChinaUnix社区介绍
ChinaUnix社区介绍
 
SIGEVOlution Spring 2007
SIGEVOlution Spring 2007SIGEVOlution Spring 2007
SIGEVOlution Spring 2007
 
Cilmatic Risk Assessment Of Southern Express Way in Sri Lanka
Cilmatic Risk Assessment Of Southern Express Way in Sri LankaCilmatic Risk Assessment Of Southern Express Way in Sri Lanka
Cilmatic Risk Assessment Of Southern Express Way in Sri Lanka
 
关于 Twitter 以及 Twitter 与 NGO2.0
关于 Twitter 以及 Twitter 与 NGO2.0关于 Twitter 以及 Twitter 与 NGO2.0
关于 Twitter 以及 Twitter 与 NGO2.0
 
2011 expoward primaria 6to. año c2
2011 expoward primaria 6to. año c22011 expoward primaria 6to. año c2
2011 expoward primaria 6to. año c2
 
Randall Santos - Portfolio 2008
Randall Santos - Portfolio 2008Randall Santos - Portfolio 2008
Randall Santos - Portfolio 2008
 
Beijing2011
Beijing2011Beijing2011
Beijing2011
 
4-31 NTC Information Sheet SEP 2012
4-31 NTC Information Sheet SEP 20124-31 NTC Information Sheet SEP 2012
4-31 NTC Information Sheet SEP 2012
 
Jeffrey Sachs
Jeffrey SachsJeffrey Sachs
Jeffrey Sachs
 
Poster the physiological effects of obesity on body system latest
Poster the physiological effects of obesity on body system latestPoster the physiological effects of obesity on body system latest
Poster the physiological effects of obesity on body system latest
 
DMI Light Towers - Operational Manual
DMI Light Towers - Operational ManualDMI Light Towers - Operational Manual
DMI Light Towers - Operational Manual
 

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

React Native Evening
React Native EveningReact Native Evening
React Native Evening
Troy Miles
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
Oswald Campesato
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
Universe41
 
fundamentals of JavaScript for students.ppt
fundamentals of JavaScript for students.pptfundamentals of JavaScript for students.ppt
fundamentals of JavaScript for students.ppt
dejen6
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
Kevin Hazzard
 
Intro to React
Intro to ReactIntro to React
Intro to React
Troy Miles
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
Justin Alexander
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
Ramamohan Chokkam
 
Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!
Ortus Solutions, Corp
 
Technology: A Means to an End with Thibault Imbert
Technology: A Means to an End with Thibault ImbertTechnology: A Means to an End with Thibault Imbert
Technology: A Means to an End with Thibault Imbert
FITC
 
FITC '14 Toronto - Technology, a means to an end
FITC '14 Toronto - Technology, a means to an endFITC '14 Toronto - Technology, a means to an end
FITC '14 Toronto - Technology, a means to an end
Thibault Imbert
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
Troy Miles
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
Alexis Gallagher
 
AkJS Meetup - ES6++
AkJS Meetup -  ES6++AkJS Meetup -  ES6++
AkJS Meetup - ES6++
Isaac Johnston
 
Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3
Mohd Harris Ahmad Jaal
 
JS Fest 2018. Douglas Crockford. The Better Parts
JS Fest 2018. Douglas Crockford. The Better PartsJS Fest 2018. Douglas Crockford. The Better Parts
JS Fest 2018. Douglas Crockford. The Better Parts
JSFestUA
 
CSC PPT 13.pptx
CSC PPT 13.pptxCSC PPT 13.pptx
CSC PPT 13.pptx
DrRavneetSingh
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02
Ramamohan Chokkam
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
Domenic Denicola
 

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

React Native Evening
React Native EveningReact Native Evening
React Native Evening
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
 
Basics of Javascript
Basics of JavascriptBasics of Javascript
Basics of Javascript
 
fundamentals of JavaScript for students.ppt
fundamentals of JavaScript for students.pptfundamentals of JavaScript for students.ppt
fundamentals of JavaScript for students.ppt
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Es6 hackathon
Es6 hackathonEs6 hackathon
Es6 hackathon
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!Introducing BoxLang : A new JVM language for productivity and modularity!
Introducing BoxLang : A new JVM language for productivity and modularity!
 
Technology: A Means to an End with Thibault Imbert
Technology: A Means to an End with Thibault ImbertTechnology: A Means to an End with Thibault Imbert
Technology: A Means to an End with Thibault Imbert
 
FITC '14 Toronto - Technology, a means to an end
FITC '14 Toronto - Technology, a means to an endFITC '14 Toronto - Technology, a means to an end
FITC '14 Toronto - Technology, a means to an end
 
Node Boot Camp
Node Boot CampNode Boot Camp
Node Boot Camp
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
AkJS Meetup - ES6++
AkJS Meetup -  ES6++AkJS Meetup -  ES6++
AkJS Meetup - ES6++
 
Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3Web Application Development using PHP Chapter 3
Web Application Development using PHP Chapter 3
 
JS Fest 2018. Douglas Crockford. The Better Parts
JS Fest 2018. Douglas Crockford. The Better PartsJS Fest 2018. Douglas Crockford. The Better Parts
JS Fest 2018. Douglas Crockford. The Better Parts
 
CSC PPT 13.pptx
CSC PPT 13.pptxCSC PPT 13.pptx
CSC PPT 13.pptx
 
Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02Jsonsaga 100605143125-phpapp02
Jsonsaga 100605143125-phpapp02
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 

Recently uploaded

Folding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a seriesFolding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a series
Philip Schwarz
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
SimonedeGijt
 
Splunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptxSplunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptx
sudsdeep
 
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdfWhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
onemonitarsoftware
 
Prada Group Reports Strong Growth in First Quarter …
Prada Group Reports Strong Growth in First Quarter …Prada Group Reports Strong Growth in First Quarter …
Prada Group Reports Strong Growth in First Quarter …
908dutch
 
Building infrastructure with code_ A deep dive into CDK for IaC in Java.pdf
Building infrastructure with code_ A deep dive into CDK for IaC in Java.pdfBuilding infrastructure with code_ A deep dive into CDK for IaC in Java.pdf
Building infrastructure with code_ A deep dive into CDK for IaC in Java.pdf
mohitd6
 
ENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentationENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentation
sofiafernandezon
 
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
ashiklo9823
 
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
Hironori Washizaki
 
Google ML-Kit - Understanding on-device machine learning
Google ML-Kit - Understanding on-device machine learningGoogle ML-Kit - Understanding on-device machine learning
Google ML-Kit - Understanding on-device machine learning
VishrutGoyani1
 
ThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and DjangoThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and Django
akshesh doshi
 
Leading Project Management Tool Taskruop.pptx
Leading Project Management Tool Taskruop.pptxLeading Project Management Tool Taskruop.pptx
Leading Project Management Tool Taskruop.pptx
taskroupseo
 
active-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptxactive-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptx
sudsdeep
 
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Asher Sterkin
 
Top 10 Tips To Get Google AdSense For Your Website
Top 10 Tips To Get Google AdSense For Your WebsiteTop 10 Tips To Get Google AdSense For Your Website
Top 10 Tips To Get Google AdSense For Your Website
e-Definers Technology
 
Addressing the Top 9 User Pain Points with Visual Design Elements.pptx
Addressing the Top 9 User Pain Points with Visual Design Elements.pptxAddressing the Top 9 User Pain Points with Visual Design Elements.pptx
Addressing the Top 9 User Pain Points with Visual Design Elements.pptx
Sparity1
 
introduction of Ansys software and basic and advance knowledge of modelling s...
introduction of Ansys software and basic and advance knowledge of modelling s...introduction of Ansys software and basic and advance knowledge of modelling s...
introduction of Ansys software and basic and advance knowledge of modelling s...
sachin chaurasia
 
What is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for FreeWhat is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for Free
TwisterTools
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
ssuser2b426d1
 
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
onemonitarsoftware
 

Recently uploaded (20)

Folding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a seriesFolding Cheat Sheet #7 - seventh in a series
Folding Cheat Sheet #7 - seventh in a series
 
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptxWired_2.0_Create_AmsterdamJUG_09072024.pptx
Wired_2.0_Create_AmsterdamJUG_09072024.pptx
 
Splunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptxSplunk_Remote_Work_Insights_Overview.pptx
Splunk_Remote_Work_Insights_Overview.pptx
 
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdfWhatsApp Tracker -  Tracking WhatsApp to Boost Online Safety.pdf
WhatsApp Tracker - Tracking WhatsApp to Boost Online Safety.pdf
 
Prada Group Reports Strong Growth in First Quarter …
Prada Group Reports Strong Growth in First Quarter …Prada Group Reports Strong Growth in First Quarter …
Prada Group Reports Strong Growth in First Quarter …
 
Building infrastructure with code_ A deep dive into CDK for IaC in Java.pdf
Building infrastructure with code_ A deep dive into CDK for IaC in Java.pdfBuilding infrastructure with code_ A deep dive into CDK for IaC in Java.pdf
Building infrastructure with code_ A deep dive into CDK for IaC in Java.pdf
 
ENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentationENISA Threat Landscape 2023 documentation
ENISA Threat Landscape 2023 documentation
 
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
Vip Girls Call ServiCe Hyderabad 0000000000 Pooja Best High Class Hyderabad A...
 
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
COMPSAC 2024 D&I Panel: Charting a Course for Equity: Strategies for Overcomi...
 
Google ML-Kit - Understanding on-device machine learning
Google ML-Kit - Understanding on-device machine learningGoogle ML-Kit - Understanding on-device machine learning
Google ML-Kit - Understanding on-device machine learning
 
ThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and DjangoThaiPy meetup - Indexes and Django
ThaiPy meetup - Indexes and Django
 
Leading Project Management Tool Taskruop.pptx
Leading Project Management Tool Taskruop.pptxLeading Project Management Tool Taskruop.pptx
Leading Project Management Tool Taskruop.pptx
 
active-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptxactive-directory-auditing-solution (2).pptx
active-directory-auditing-solution (2).pptx
 
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
Ported to Cloud with Wing_ Blue ZnZone app from _Hexagonal Architecture Expla...
 
Top 10 Tips To Get Google AdSense For Your Website
Top 10 Tips To Get Google AdSense For Your WebsiteTop 10 Tips To Get Google AdSense For Your Website
Top 10 Tips To Get Google AdSense For Your Website
 
Addressing the Top 9 User Pain Points with Visual Design Elements.pptx
Addressing the Top 9 User Pain Points with Visual Design Elements.pptxAddressing the Top 9 User Pain Points with Visual Design Elements.pptx
Addressing the Top 9 User Pain Points with Visual Design Elements.pptx
 
introduction of Ansys software and basic and advance knowledge of modelling s...
introduction of Ansys software and basic and advance knowledge of modelling s...introduction of Ansys software and basic and advance knowledge of modelling s...
introduction of Ansys software and basic and advance knowledge of modelling s...
 
What is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for FreeWhat is OCR Technology and How to Extract Text from Any Image for Free
What is OCR Technology and How to Extract Text from Any Image for Free
 
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTIONBITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
BITCOIN HEIST RANSOMEWARE ATTACK PREDICTION
 
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
Discover the Power of ONEMONITAR: The Ultimate Mobile Spy App for Android Dev...
 

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

  • 1. Hands on: The sexy side of JavaScript (feat. node.js) @pirafrankfpira.com Francesco Pira Google #io16 Extended Catania
  • 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!)
  • 5. fpira.com ECMAScript, actually… • Official language name • Versions often abbreviated as 'ESx' • ES3 = 1999; • var ES5 = 2015; • const ES6 = 2016; • (ES7 is WIP…)
  • 7. !==
  • 8. fpira.com nvm • nvm : node version manager (bash script) • $ nvm install 6.1.0
  • 9. fpira.com Types • Number (dp 64 bit) • String • Boolean • Object • function, Array, • Date, RegExp • Symbol (ES6+) • NaN • Special objects • undefined • null
  • 10. fpira.com Truthy and falsy • true • non-zero numbers • "strings" • objects • arrays • functions • false • 0 • "" • undefined • null • NaN
  • 11. fpira.com Flow control • Conditional statements • Exception handling statements • Promises (since ES6)
  • 12. 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; }
  • 13. 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++; }
  • 14. 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" }
  • 15. fpira.com Exception handling • throw • try…catch • try…catch…finally openMyFile(); try { writeMyFile(theData); } catch(e) { handleError(e); } finally { closeMyFile(); } throw expression;
  • 16. 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");
  • 17. 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
  • 18. 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" } ] }
  • 19. 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
  • 20. 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
  • 21. 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']
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. fpira.com …there’s more! • Symbols • Iterators and Generators • new Array methods • Map, Set • functional programming in JS ES6
  • 28. 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"
  • 29. fpira.com Why node.js? • Event driven • Async I/O • Non-blocking calls • Single-threaded • Thousands of concurrent connections • Great in cluster environment
  • 30. fpira.com npm • npm : node package manager • $ npm install -g gulp • $ npm … • init • install • start • test • etc.
  • 31. fpira.com App structure • package.json • node_modules • test • src/app • …
  • 32. 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');
  • 33. 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
  • 34. 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
  • 35. 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
  • 37. 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}/`); });
  • 38. 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
  • 39. 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)
  • 40. fpira.com Next (more) • Gulp • Babel • TypeScript • Read about JS functional programming • (https://medium.com/@chetcorcos/functional-programming-for-javascript- people-1915d8775504#.bawhglud6)