Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JavaScript - Mandatory Fun

JavaScript - Mandatory Fun

Introductory talk to javascript.

Avatar for Cosmin 'cosu' Dumitru

Cosmin 'cosu' Dumitru

November 11, 2015

Other Decks in Programming

Transcript

  1. 2 VANITY SLIDE Cosmin 'cosu' Dumitru OS3 alumni 2009 -

    2010 PhD Student in the SNE group 2010 - 2015 Consultant - Software Improvement Group
  2. 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
  3. 5 WHY SHOULD YOU CARE Everywhere - (almost) any browser!

    It’s easy (and it’s becoming easier) Powerful (functional, async support, high performance) You’ll have to anyway
  4. 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"
  5. 8 ECMASCRIPT The language specification ( June 1997) Implementations JavaScript

    - most popular ActionScript 3 - ES4 + extensions JScript - Microsoft
  6. 9 ECMASCRIPT (2) ECMAScript Version 3 - Dec. 1999 ECMAScript

    Version 4 - abandoned due to political differences 2005 - Jesse James Garrett writes the Ajax ECMAScript Version 5 (or 3.1) - Dec. 2009 'strict mode' to prevent common error constructs ECMAScript Version 6 - June 2015 classes, modules, generators, collections white paper
  7. 10 JAVASCRIPT Structured if , for, while, code blocks Dynamic

    most type information at runtime Functional programming done by evaluating expressions Prototype based reusing is done by cloning existing objects "The world's most misunderstood programming language"
  8. 11 SYNTAX function 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
  9. 12 LANGUAGE TYPES Dynamic typing - variable types are not

    declared var x = 0; // Number x = "foo"; // String x = Symbol("foo"); // new in ES6 x = false; // Boolean x = null // Null x = undefined // Undefined x = {}; // Object - not a privimite type
  10. 13 NUMBERS IEEE 754 format - 64 bit floating point

    No Integer type Read var x = 0.1 + 0.2; > 0.30000000000000004 What Every Computer Scientist Should Know About Floating-Point Arithmetic
  11. 14 OBJECTS Collection of properties Created using the Object contructor

    or the {} literal Properties = Keys (Names) and Values Keys can be Strings and Symbols Values can be of any type var shirt = {}; shirt.size = 'LARGE' shirt['size'] > [ 'LARGE' ]
  12. 15 ARRAYS List-like objects Created using the Array contructor or

    the [] literal var arr = ['foo', 'bar']; arr.length > 2 arr[0] > 'foo' arr.push('baz') > [ 'foo', 'bar', 'baz' ]
  13. 16 TRUTHY all of these are equivalent if (true) if

    ({}) if ([]) if (42) if ("foo") if (new Object())
  14. 17 FALSY all of these are equivalent if (false) if

    (null) if (undefined) if (0) if (NaN) if ('') if (document.all) // srsly
  15. 18 OPERATORS Arithmetic : + - * / % ++

    -- Assignment : += -= *= /= %= Logical: && || Compaison Javscript performs automatic type coercion! == != equal (value only) === !== strict equal (type and value) 2 == '2' // true 2 === '2' // false 1 == true //true 1 === true // false "a" === new String("a") // false //string vs Object
  16. 19 FUNCTIONS Logical units that implement a piece of functionality

    and always 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
  17. 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
  18. 21 FUNCTIONS (3) first class objects - can be passed

    arround like any other type function 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); > 42 compute (6,7, add) > 13
  19. 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'
  20. 23 FUNCTION-LEVEL SCOPE function foo(){ console.log(i); for (var i =

    0; i < 10; i ++) { // bla } console.log(j); } foo(); undefined ReferenceError: j is not defined
  21. 24 SCOPE AND HOISTING First variables are declared but not

    initialized Functions 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
  22. 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
  23. 26 CLOSURES (2) Module pattern - private variables function 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
  24. 27 INHERITANCE JavaScript has no classes ES6 adds syntactic sugar

    for classes Prototype 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 implementation a.x > 1 a.y = 42; b.y // delegate to the protoptype > 42
  25. 28 CALLBACKS A function passed to another function as parameter

    $('#button').on('click',function(){ $.get("https://api.github.com", function(response){ console.log(response); }); });
  26. 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
  27. 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
  28. 31 PROMISES Promise = eventual result of an async operation

    Pending -> Fulfilled or Rejected Pipelining and better structuring of callbacks
  29. 32 PROMISES(2) Demo var apiUrl = "https://api.github.com/search/repositories?q=promise&sort=stars&o 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"); });
  30. 33 JSON JavaScript Object Notation Data objects - key, value

    pairs Demo { 'price': 1000, 'description': 'Item1' 'type': 'bike' 'created': 1447192495275 }
  31. 34 JAVASCRIPT ENGINES v8 - OSS JavaScript engine Chrome, Node.js

    SpiderMonkey - Mozilla Chakra - Used in IE Nashhorn - embedded in Oracle JDK JavaScriptCore - used in Safari Others
  32. 35 NODE.JS Server side JavaScript using V8 Event driven, non

    blocking Modules for IO, binary handling, crypto
  33. 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/");
  34. 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/");
  35. 38 NPM Node package manager package.json - versions of dependencies,

    metadata npm install jslint { "name" : "foo", "version" : "0.0.0", "dependencies": { "bar": "1.0.42", }, }
  36. 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; });
  37. 41 OTHER TOPICS NOT COVERED this, bind, call, apply Implementing

    classes Execution contexts Put effort into understanding them! (see refs.)
  38. 42 TRANSPILERS 'JavaScript is the Assembly Language of the Web'

    Emscripten - LLVM to JavaScript asm.js / WebAssembly low level high performance
  39. 43 COFFEESCRIPT syntactic sugar for JavaScript shorter, more concise code

    //JavaScript var mul = function(a,b){ return a*b; } //CoffeeScript mul = (a,b)-> a*b
  40. 44 DART Classes, type annotations, async/await Familiar syntax dart2Js /

    Dartium / Standalone Targets for mobile, desktop and system applications
  41. 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() {
  42. 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()); }
  43. 48 OTHER COOL THINGS Flow - 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.js Babel.js Crossfilter
  44. 49 SOME RESOURCES Crockford on Javascript You Don't know JS

    Pro Javascript Speaking JavaScript Javascript Alonge Exploring ES6 Essential JavaScript Links