Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
1
JAVASCRIPT
MANDATORY FUN!
COSMIN DUMITRU
11 NOVEMBER 2015
2
VANITY SLIDECosmin 'cosu' Dumitru
OS3 alumni 2009 - 2010
PhD Student in the SNE group 2010 - 2015
Consultant - Software Improvement Group
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
4
JAVA VS JAVASCRIPT
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
6
GITHUT
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"
8
ECMASCRIPTThe language specification ( June 1997)Implementations
JavaScript - most popularActionScript 3 - ES4 + extensionsJScript - Microsoft
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
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"
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
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
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
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' ]
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' ]
16
TRUTHY
all of these are equivalent
if (true)if ({})if ([])if (42)if ("foo")if (new Object())
17
FALSYall of these are equivalent
if (false)if (null)if (undefined)if (0)if (NaN)if ('')if (document.all) // srsly
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
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
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
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
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'
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
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
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
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
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
28
CALLBACKSA function passed to another function as parameter
$('#button').on('click',function(){ $.get("https://api.github.com", function(response){ console.log(response); });});
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
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
31
PROMISES
Promise = eventual result of an async operationPending -> Fulfilled or RejectedPipelining and better structuring of callbacks
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");
});
33
JSON
JavaScript Object Notation
Data objects - key, value pairs
Demo
{ 'price': 1000, 'description': 'Item1' 'type': 'bike' 'created': 1447192495275}
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
35
NODE.JS
Server side JavaScript using V8
Event driven, non blocking
Modules for IO, binary handling, crypto
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/");
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/");
38
NPMNode package manager
package.json - versions of dependencies, metadata
npm install jslint
{ "name" : "foo", "version" : "0.0.0", "dependencies": { "bar": "1.0.42", },}
39
MODULECOUNTS
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; });
41
OTHER TOPICS NOTCOVERED
this, bind, call, applyImplementing classesExecution contextsPut effort into understanding them! (see refs.)
42
TRANSPILERS'JavaScript is the Assembly Language of the Web'Emscripten - LLVM to JavaScriptasm.js / WebAssembly
low levelhigh performance
43
COFFEESCRIPT
syntactic sugar for JavaScriptshorter, more concise code
//JavaScriptvar mul = function(a,b){ return a*b;}//CoffeeScriptmul = (a,b)-> a*b
44
DARTClasses, type annotations, async/awaitFamiliar syntaxdart2Js / Dartium / StandaloneTargets for mobile, desktop and system applications
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() {
46
TYPESCRIPTClasses, type annotations, async/awaitSuperset of JavaScriptTranspiles to ES6
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());}
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
49
SOME RESOURCES
Crockford on JavascriptYou Don't know JSPro JavascriptSpeaking JavaScriptJavascript AlongeExploring ES6Essential JavaScript Links
50 . 1
THANK YOU!