javascript mandatory fun! - os3 · 11/11/2015  · javascript structured if , for, while, code...

50
1 JAVASCRIPT MANDATORY FUN! COSMIN DUMITRU 11 NOVEMBER 2015

Upload: others

Post on 20-Jun-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

1

JAVASCRIPT

MANDATORY FUN!

COSMIN DUMITRU

11 NOVEMBER 2015

Page 2: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

2

VANITY SLIDECosmin 'cosu' Dumitru

OS3 alumni 2009 - 2010

PhD Student in the SNE group 2010 - 2015

Consultant - Software Improvement Group

Page 3: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

3

THIS TALK

High level overview of JavaScript and some related

concepts

JavaScript ecosystem: node, databases

You will not be an expert in JavaScript by the end of it

unless you already are :)

Main goal: arouse your curiosity

Page 4: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

4

JAVA VS JAVASCRIPT

Page 5: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

5

WHY SHOULD YOUCARE

Everywhere - (almost) any browser!It’s easy (and it’s becoming easier)Powerful (functional, async support, high performance)You’ll have to anyway

Page 6: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

6

GITHUT

Page 7: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

7

ORIGINS

created by Brendan Eich in 10 days - Mocha (May 1995)LiveScript (September 1995)JavaScript (December 1995)

Released with Netscape Navigator 2.0

navigator.appName> "Netscape"

Page 8: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

8

ECMASCRIPTThe language specification ( June 1997)Implementations

JavaScript - most popularActionScript 3 - ES4 + extensionsJScript - Microsoft

Page 9: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

9

ECMASCRIPT (2)ECMAScript Version 3 - Dec. 1999ECMAScript Version 4 - abandoned due to politicaldifferences

2005 - Jesse James Garrett writes the Ajax ECMAScript Version 5 (or 3.1) - Dec. 2009

'strict mode' to prevent common error constructsECMAScript Version 6 - June 2015

classes, modules, generators, collections

white paper

Page 10: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

10

JAVASCRIPT

Structuredif , for, while, code blocks

Dynamicmost type information at runtime

Functionalprogramming done by evaluating expressions

Prototype basedreusing is done by cloning existing objects

"The world's most misunderstood programminglanguage"

Page 11: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

11

SYNTAXfunction countWords(input) { var count = 0; for (var i=0; i < input.length; i ++) { if (input.charAt(i) === ' ') count++; } return count + 1;}

> countWords('all your base are belong to us!')> 7

Page 12: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

12

LANGUAGE TYPESDynamic typing - variable types are not declared

var x = 0; // Numberx = "foo"; // Stringx = Symbol("foo"); // new in ES6x = false; // Booleanx = null // Nullx = undefined // Undefinedx = {}; // Object - not a privimite type

Page 13: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

13

NUMBERSIEEE 754 format - 64 bit floating point

No Integer type

Read

var x = 0.1 + 0.2;> 0.30000000000000004

What Every Computer Scientist Should Know AboutFloating-Point Arithmetic

Page 14: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

14

OBJECTS

Collection of propertiesCreated using the Object contructor or the {} literalProperties = Keys (Names) and ValuesKeys can be Strings and Symbols

Values can be of any type

var shirt = {};shirt.size = 'LARGE'shirt['size']> [ 'LARGE' ]

Page 15: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

15

ARRAYSList-like objects

Created using the Array contructor or the [] literal

var arr = ['foo', 'bar'];arr.length> 2arr[0]> 'foo'arr.push('baz')> [ 'foo', 'bar', 'baz' ]

Page 16: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

16

TRUTHY

all of these are equivalent

if (true)if ({})if ([])if (42)if ("foo")if (new Object())

Page 17: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

17

FALSYall of these are equivalent

if (false)if (null)if (undefined)if (0)if (NaN)if ('')if (document.all) // srsly

Page 18: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

18

OPERATORS

Arithmetic : + - * / % ++ --Assignment : += -= *= /= %=Logical: && ||Compaison

Javscript performs automatic type coercion!== != equal (value only)

=== !== strict equal (type and value)

2 == '2' // true2 === '2' // false1 == true //true1 === true // false"a" === new String("a") // false//string vs Object

Page 19: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

19

FUNCTIONS

Logical units that implement a piece of functionality andalways return a value

Arguments are passed by value for primitive types

function censor(text) {// all characters become # text = text.replace(/\w/g,"#"); return text;}var password = "foo"console.log(censor(password));console.log(password);> '###'> 'foo' // password is unchanged

Page 20: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

20

FUNCTIONS(2)

Arguments are passed by reference for object types

function censor(user) { user.password = user.password.replace(/\w/g,"#"); return user;}var user = {password: 'foo'};console.log(censor(user).password);console.log(user.password);> '###'> '###' // password is changed

Page 21: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

21

FUNCTIONS (3)

first class objects - can be passed arround like any othertypefunction add(a,b){ return a + b}

function mul(a,b) { return a*b;}

function compute(a,b, f){ return f(a,b);}

compute(6,7,mul);> 42compute (6,7, add)> 13

Page 22: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

22

SCOPE

Only functions can create a new scope - function-level

scope

Scope is defined statically - lexical scoping

var x = 'spam'; // global scope

function bar () { var x = 'eggs'; // local scope console.log(x); foo();}function foo(){ console.log(x); // from global}bar()> 'eggs'> 'spam'

Page 23: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

23

FUNCTION-LEVEL

SCOPE

function foo(){ console.log(i);

for (var i = 0; i < 10; i ++) { // bla } console.log(j);}

foo();

undefinedReferenceError: j is not defined

Page 24: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

24

SCOPE AND HOISTINGFirst variables are declared but not initializedFunctions are 'hoisted'

var x = 42;function foo() { bar(); if (!x) { // x === undefined var x = 0; } function bar(){ console.log(x); } console.log(x);}

foo();

undefined> 0

Page 25: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

25

CLOSURES

Function definition + enviroment

function foo(){ var x = 42; function bar(){ console.log(x); } return bar;}

var baz = foo();baz() // bar holds a reference to foo's scope

> 42

Page 26: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

26

CLOSURES (2)

Module pattern - private variablesfunction myCounter(){ var counter = 0; return { inc: function () { return counter++; }, reset: function () { console.log( " reset: " + counter); counter = 0; } }}var c = myCounter()c.inc();c.reset();> reset: 4

Page 27: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

27

INHERITANCE

JavaScript has no classesES6 adds syntactic sugar for classesPrototype chain - objects are linked to their "prototype"var a = { x : 1 };var b = Object.create(a); //link b to a

b.x // shadowing a.x> 1

b.x = 2 // override with own implementationa.x

> 1

a.y = 42;

b.y // delegate to the protoptype> 42

Page 28: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

28

CALLBACKSA function passed to another function as parameter

$('#button').on('click',function(){ $.get("https://api.github.com", function(response){ console.log(response); });});

Page 29: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

29

EVENT LOOP

single threaded processing

run-to-completion

never blocking - IO operations take place in the

background

while ( true ) { work = queue.take(); process(work);}

Event loop visualized

Page 30: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

30

"PYRAMID OF DOOM"

aka Callback Hell

var query = {..}Service.logIn("user", "pass", { success: function(user) { query.user = user.id; query.find({ success: function(results) { results[0].save({ credit: 42}, { success: function(result) { console.log("save success") } }); } }); }}); // it can get worse

Page 31: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

31

PROMISES

Promise = eventual result of an async operationPending -> Fulfilled or RejectedPipelining and better structuring of callbacks

Page 32: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

32

PROMISES(2)

Demovar apiUrl = "https://api.github.com/search/repositories?q=promise&sort=stars&order=desc"var jQueryPromise = $.get(apiUrl);//wrap jquery ...var realPromise = Promise.resolve(jQueryPromise);

realPromise

.then(function(response) { return response.total_count; })

.then(function(count) { console.log("Found " + count + " GitHub repos searching 'promise'"

})

.catch(function(err) { console.log("failed call");

});

Page 33: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

33

JSON

JavaScript Object Notation

Data objects - key, value pairs

Demo

{ 'price': 1000, 'description': 'Item1' 'type': 'bike' 'created': 1447192495275}

Page 34: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

34

JAVASCRIPT ENGINESv8 - OSS JavaScript engine

Chrome, Node.js

SpiderMonkey - Mozilla

Chakra - Used in IE

Nashhorn - embedded in Oracle JDK

JavaScriptCore - used in Safari

Others

Page 35: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

35

NODE.JS

Server side JavaScript using V8

Event driven, non blocking

Modules for IO, binary handling, crypto

Page 36: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

36

NODE.JS - SYNC

var http = require('http');var fs = require("fs");

var server = http.createServer(function (request, response) { response.writeHead(200, {"Content-Type": "text/plain"});

var data = fs.readFileSync('content.txt'); response.end(data+"\n");

}).listen(8000);

console.log("Server running at http://127.0.0.1:8000/");

Page 37: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

37

NODE.JS - ASYNC

var http = require('http');var fs = require("fs");

var server = http.createServer(function (request, response) { fs.readFile('content.txt', function(err, data){ response.writeHead(200, {"Content-Type": "text/plain"});

response.end(data+"\n");

});

}).listen(8000);

console.log("Server running at http://127.0.0.1:8000/");

Page 38: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

38

NPMNode package manager

package.json - versions of dependencies, metadata

npm install jslint

{ "name" : "foo", "version" : "0.0.0", "dependencies": { "bar": "1.0.42", },}

Page 39: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

39

MODULECOUNTS

Page 40: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

40

MONGODB

embedded V8 engine

uses BSON (binary JSON) to store documents

Interaction and administration via JS Shell

var itemsInUSD = db.find({ 'price':{'$gt':100} }) .map(function(item){ item.price = 1.04 * item.price; return item; });

Page 41: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

41

OTHER TOPICS NOTCOVERED

this, bind, call, applyImplementing classesExecution contextsPut effort into understanding them! (see refs.)

Page 42: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

42

TRANSPILERS'JavaScript is the Assembly Language of the Web'Emscripten - LLVM to JavaScriptasm.js / WebAssembly

low levelhigh performance

Page 43: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

43

COFFEESCRIPT

syntactic sugar for JavaScriptshorter, more concise code

//JavaScriptvar mul = function(a,b){ return a*b;}//CoffeeScriptmul = (a,b)-> a*b

Page 44: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

44

DARTClasses, type annotations, async/awaitFamiliar syntaxdart2Js / Dartium / StandaloneTargets for mobile, desktop and system applications

Page 45: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

45

DART (2)import 'dart:math' show Random;

class Vm { static final Random idGen = new Random(); String _templateName; int id; Vm(String templateName) { _templateName = templateName; id = idGen.nextInt(100);

} String toString() => "$_templateName-$id";

}

void main() {

Page 46: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

46

TYPESCRIPTClasses, type annotations, async/awaitSuperset of JavaScriptTranspiles to ES6

Page 47: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

47

TYPESCRIPT (2)class Vm { private templateName: string; private id: number; constructor(templateName: string) { this.templateName = templateName; this.id = Math.floor(Math.random() * 100); } toString(): string { return `${this.templateName}-${this.id}`; }}

for ( var i = 0; i < 5; i++) { var vm = new Vm("foo"); console.log(vm.toString());}

Page 48: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

48

OTHER COOL THINGSFlow - static type checker

- write scala and compile to JavaScript - Use future features now!

TypeScript -> ES6 -> Babel -> ES5

Data visualization -

function mul(a, b){return a*b;}mul ("foo", "bar"); // NaN

Scala.jsBabel.js

Crossfilter

Page 49: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

49

SOME RESOURCES

Crockford on JavascriptYou Don't know JSPro JavascriptSpeaking JavaScriptJavascript AlongeExploring ES6Essential JavaScript Links

Page 50: JavaScript Mandatory Fun! - OS3 · 11/11/2015  · JAVASCRIPT Structured if , for, while, code blocks Dynamic most type information at runtime Functional programming done by evaluating

50 . 1

THANK YOU!