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

JavaScript Development

JavaScript Development

Under

Jussi Pohjolainen

November 22, 2016
Tweet

More Decks by Jussi Pohjolainen

Other Decks in Technology

Transcript

  1. Recommended Reading • Recommended reading • JavaScript: The Good Parts

    by Douglas Crockford • JavaScript: The Definite Guide by David Flanagan • JavaScript Patterns: Stoyan Stefanov • And Google..
  2. JavaScript today • The key language to implement web applications

    • Building universal Windows 10 applications • Possible candidate for cross-platform mobile development • Cordova / Phonegap, Ionic • Also server side development (Backend) • Replacing / Complementing XML for data transfer (REST + JSON)
  3. Responsive • Unified across experiences • Can be embedded as

    mobile app • Better deployment and & maintanence • Mobile users need to get access to everything Image: http://coenraets.org/blog/wp-content/uploads/2011/10/directory11.png
  4. Single-page Applications (SPA) • Web app that fits on a

    single web page • Fluid UX, like desktop app • Examples like Gmail, Google maps • Html page contains mini-views (HTML Fragments) that can be loaded in the background • No reloading of the page, better UX • Requires handling of browser history, navigation and bookmarks
  5. Rise of the REST and JSON • REST is a

    one way of communicating between computers over the internet • Data can be send via XML or JSON using HTTP • HTTP GET • http://something/employee/1 • Result • {id: 1, name: "jack"} • If both frontend and backend is JS, object sending and parsing extremely easy
  6. Rise of the JS Backend: NodeJS • Open source JS

    runtime environment • Uses V8 (Chrome) JS engine • Additional modules on top of JS to provide functionality • Web server, system i/o, networking, ... • Lot of third party modules available
  7. Native iOS App iOS WebView index.html app.js angularjs.js ionic.js cordova.js

    stylesheet.css Native Android App Android WebView index.html app.js angularjs.js ionic.js cordova.js stylesheet.css Using Cordova it's possible to access mobile device native features Web Server Node.js + Express + Mongo app.js package.json modules/express/ modules/mongodb/ MongoDB [{name: 'jack'}, {name: 'tina'}, {..}, {..}] HTTP GET (ajax) Request: http://server.com/employees/1 HTTP Response content-type: application/json {name: 'jack'} Frontend Ionic + Cordova + AngularJS Backend Node.JS + Express + Mongo HTTP POST Request: http://server.com/employees/ {name: 'amanda'} HTTP Response content-type: text/plain http://server.com/employees/3 Communication REST and JSON
  8. Web Standards? • Formal standards or technical specifications that describe

    the World Wide Web • Web Standards consist of the following • Recommendations of the World Wide Web Consortium (W3C) • (X)HTML, CSS, SVG, DOM ... • RFC documents published by Internet Engineering Task Force (IETF) • URI, HTTP, MIME ... • And also standards by Ecma International (JavaScript), Unicode (Charsets) and IANA (Name and number registries).
  9. World Wide Web Consortium • The World Wide Web Consortium

    (W3C) is the main international standards organization for the World Wide Web • Compatibility among industry members • W3C makes recommendations for the web • Several recommendations • XHTML, DOM, CSS, XML... • URL: http://www.w3.org/
  10. JavaScript, LiveScript, JScript, ECMAScript? • JavaScript • Developed by Netscape

    • Originally JavaScript, then LiveScript and then back to JavaScript. • JScript • Microsoft made their own version of the JavaScript • Lead to compatibility problems • => ECMAScript, effort to standardize different versions of the J(ava)Script
  11. ECMAScript • ECMAScript is a scripting language, standardized by Ecma

    International • In Browsers, ECMAScript is commonly called JavaScript • JavaScript = Native (EcmaScript) + Host objects (browser) • Java/ECMAscript is nowdays heavily used with AJAX – based sites • Still many problems because of browser incompatibilites
  12. EcmaScript Versions Year Edition Naming 1997 1 .. 1998 2

    .. 1999 3 Regex, better string handling, try/catch,... Abandoned 4 .. 2009 5 strict mode, getters and setters, JSON.. 2015 6 ES2015 classes, modules, arrow functions, collections ... 2016 7 ES2016 ..
  13. From JScript to TypeScript • TypeScript is a superset of

    EcmaScript developed by Microsoft • It has types! • When EcmaScript 6th Edition was working progress, typescript gave already classes, modules, arrow function syntax. • Now that the 6th Ed. is ready the additional benefit using TypeScript is types (and others like interfaces, generics...) • TypeScript is compiled to EcmaScript using compiler • It's first class language in Microsoft Visual Studio and in frameworks like Angular 2.0
  14. typescript.ts > cat typescript.ts var variable : string = "typescript";

    console.log(variable); > tsc typescript.ts > cat typescript.js var variable = "typescript"; console.log(variable); Notice that compiler compiles typescript to javascript and it loses the string type because that is not part of js!
  15. Benefit of using Compiler > cat typescript.ts var variable :

    string = "typescript"; variable = 8; console.log(variable); > tsc typescript.ts typescript.ts(2,1): error TS2322: Type 'number' is not assignable to type 'string'.
  16. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">

    <head> <title>Embed Example</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" /> </head> <body> <p> <script type="text/javascript"> //<![CDATA[ document.write("Hello from JS!"); //]]> </script> </p> </body> </html>
  17. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">

    <head> <title>External JS Example</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" /> <script type="text/javascript" src="event.js"></script> </head> <body onload="message()"> </body> </html>
  18. ECMAScript • ECMAScript is a scripting language, standardized by Ecma

    International • ECMAScript is commonly called JavaScript when having host objects • JavaScript = Native (EcmaScript) + Host objects • Host objects can be objects from browser environment or for example from NodeJS
  19. Primitive Types • JavaScript is loosely typed language! • Six

    primitive datatypes • Boolean (true, false) • Null (value that isn’t anything) • Undefined (undefined value) • Number - floating point number (64 bit) • String (16 bit UNICODE) • Symbol (ECMAScript 6) • And Objects (all the rest)
  20. Primitive Types - Testing var booleanValue = true; var stringValue

    = "some text"; var undefinedValue; var numberValue = 4; var nullValue = null; // boolean console.log(typeof booleanValue) // string console.log(typeof stringValue) // undefined console.log(typeof undefinedValue) // number console.log(typeof numberValue) // object (language design error in ECMAScript!) console.log(typeof nullValue) // false console.log(null instanceof Object)
  21. String • Series of characters • Indexes zero based, first

    char 0, second 1 • Examples • var mj1 = "hello"; • var mj2 = "hello \"world\""; • Methods available • charAt(), replace(), split() • See: • https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objects/String
  22. Automatic type conversion 5 + null // returns 5 because

    null is converted to 0 "5" + null // returns "5null" because null is converted to "null" "5" + 1 // returns "51" because 1 is converted to "1" "5" - 1 // returns 4 because "5" is converted to 5
  23. About Numbers • Number(value), converts entire string • var i

    = Number("12"); • parseInt(value[, radix]), converts start of the string • var i = parseInt("12px”, 10); • Radix? • 10 => integer number, 8 => octal number, 16 => hexadecimal • NaN (Not a Number), check using isNaN(variable) • Result of erroneous operations
  24. Date var today = new Date(); var birthday = new

    Date('December 17, 1995 03:24:00'); var birthday = new Date('1995-12-17T03:24:00'); var birthday = new Date(1995, 11, 17); var birthday = new Date(1995, 11, 17, 3, 24, 0); var unixTimestamp = Date.now(); // in milliseconds
  25. Regex • Regular expressions are patterns used to match character

    combinations in strings • In JS regex is an object • var re = new RegExp("ab+c"); • For better performance • var re = /java/; • Example var regex = new RegExp("java"); if("javascript".match(regex)) { console.log("Match found!"); }
  26. Indexed Collection: Arrays • Arrays are objects but in addition

    they have more methods and auto-increment key-values • var stuff = ["a", "b", "c"] • The keys are now 0, 1 and 2 • The length of the array is 3 and it's linked to numerical properties
  27. Array Usage var stuff = ["a", "b", "c"] console.log(stuff[0]); //

    a console.log(stuff[1]); // b console.log(stuff[2]); // c console.log(stuff.length); // 3 // Array's length and numerical properties are connected stuff.push("d") console.log(stuff.length); // 4 stuff["key"] = "value"; console.log(stuff); // [ 'a', 'b', 'c', 'd', key: 'value' ] console.log(stuff.length); // 4! delete stuff["key"]; console.log(stuff); // [ 'a', 'b', 'c', 'd' ] stuff[4] = "e"; console.log(stuff); // [ 'a', 'b', 'c', 'd', 'e' ] console.log(stuff.length); // 5 stuff = ["a", "b", "c"]; stuff[9] = "e"; console.log(stuff); // [ 'a', 'b', 'c', , , , , , , 'e' ] console.log(stuff.length); // 10
  28. JavaScript Objects • Object is an collection of key –

    value pairs (properties) • var car = { brand: "Ford", year: 2015 } • Possible to create properties dynamic • var car = new Object(); car.brand = "Ford"; • Possible to use also bracket notation • car["year"] = 2015 • Delete key-value pair • delete car["year"]
  29. Global Objects • Avoid global objects! • Global variables are

    in fact properties of the global object! • In web environment the global object is window • So • var x = 5 ó window.x = 5;
  30. Keyed Collections: Map • EcmaScript 6th ed: Map object for

    simple key-value pairs var sayings = new Map(); sayings.set("dog", "woof"); sayings.set("cat", "meow"); for (var [key, value] of sayings) { console.log(key + " goes " + value); } • Map object advantages over Objects: • Map keys can be anything, in objects it's string • Map has size information • Iteration in maps are the insert order
  31. Keyed Collections: Set • Set object is a collection of

    values var mySet = new Set(); mySet.add(1); mySet.add("some text"); mySet.add("foo"); mySet.has(1); // true mySet.delete("foo"); mySet.size; // 2 for (var item of mySet) console.log(item); • Set object advantages over arrays: • Only unique values • Checking element if exists is faster • Can delete values, in array's its splice
  32. Expressions and Operators • Assignment • var x = 5;

    x++; x += 10; • Comparison • ==, ===, <, >, <=, => ... • Arithmetic • +, /, -, * ... • Logical • &&, ||, !
  33. Input & Output – Depends! • In Browsers • Input:

    HTML Forms or window.prompt("", ""); • Output: DOM manipulation, document.write("") or window.alert(""); • In V8/NodeJS or Rhino/Spidermonkey • Output to CLI: print(".."); • Input from CLI: Is not that easy... • Debugging • console.log("");
  34. Functions • Functions are fundamental part of JS coding •

    Functions are objects! It's possible to pass them as variables • If function is object's property, it's a method • Functions uses variable hoisting, let's see this later
  35. Basic Function function add(a, b) { return a + b;

    } console.log( add(1,1) ); // THIS IS THE SAME THAN ABOVE! // Creating a function object var adder = new Function('a', 'b', 'return a + b'); console.log( adder(4,4) ); // Because it's an object you can pass these! var x = adder; console.log( x(9,9) );
  36. Function object with arguments function add(a, b) { console.log(arguments); }

    // { '0': 1, '1': 1 } add(1,1); // null console.log(add.arguments);
  37. Callbacks function doSomething(func1, func2) { if(true) { func1(); } else

    { func2(); } } function onSuccess() { console.log("Success!"); } function onFail() { console.log("Fail!"); } doSomething(onSuccess, onFail);
  38. Anonymous Functions function doSomething(func1, func2) { if(true) { func1(); }

    else { func2(); } } doSomething(function() { console.log("Success"); }, function() { console.log("Fail"); });
  39. Arrow Function (ES2015) function doSomething(func1, func2) { if (true) {

    func1(); } else { func2(); } } doSomething(() => { console.log("Success"); }, () => { console.log("fail"); });
  40. Functions and Variable Declaring var x = 10; function test()

    { console.log(x); // outputs what? if(true) { var x = 5; } } test();
  41. Variable Hoisting! var x = 10; function test() { var

    x; console.log(x); // outputs “undefined” if(true) { x = 5; } } test();
  42. Variables inside of Function function test() { var x =

    12; if(true) { // The same variable than the x above! var x = 13; } // Prints 13 console.log(x); } test();
  43. Single Var Pattern function test() { var a = 1,

    b = 2, …; // rest of the function } test();
  44. EcmaScript 2015: let function test() { let x = 12;

    if(true) { // Different variable than the x above! var x = 13; } // Prints 12 console.log(x); } test();
  45. Function Declaration: this works! function testC() { print(foo()); function foo()

    { return 5; } } <=> function testD() { function foo() { return 5; } print(foo()); }
  46. Function Expression: this does not work! function testA() { print(foo());

    var foo = function() { return 5; } } <=> function testB() { var foo; print(foo()); foo = function() { return 5; } }
  47. Named Function Expression // Named function expression for recursion or

    debugging var somethingFoo = function somethingBar() { print("do something"); // Recursion, does not end well here. somethingBar(); } somethingFoo(); // this does not work somethingBar();
  48. Functions in if-statements function init() { if(true) { function foo()

    { return 1; } } else { function foo() { return 2; } } return foo(); } print(init()); // 1 or 2?
  49. Use this! function init2() { var foo; if(true) { foo

    = function() { return 1; } } else { foo = function() { return 2; } } return foo(); } print(init2());
  50. CLI • We have now stayed in browser environment •

    For more professional approach, let's dive into cli and create our apps without the browser • Very useful / efficient when creating large scale JS apps
  51. JS and Command Line • It’s possible to run your

    js apps in command line. • Several JS engines • SpiderMonkey (c++) or Rhino (java) (Firefox) • SquirrelFish (Apple’s Webkit) • V8 (Google Chrome) • It’s possible to install these as command line apps, although the process can be little difficult
  52. Rhino (JavaScript Engine) • Open Source JS Engine developed in

    Java • Mozilla Foundation • No built in support for web browser objects • Has Rhino shell for running JS in command line • Is bundled in Java SE 6
  53. About Objects • Everything (except basic types) are objects •

    Including functions and arrays • Object contains properties and methods • Collection of name-value pairs • Names are strings, values can be anything • Properties and methods can be added at runtime • Objects can inherit other objects
  54. Object Literal var mystring = “hello!”; var myarray = [“element1”,

    “element2”]; var myboolean = true; var circle1 = {radius: 9, getArea : someFunction }; var circle2 = { radius: 9, getRadius: function() { return this.radius; } }
  55. No Classes! • One of the simplest way to create

    object var obj = new Object(); obj.x = 10; obj.y = 12; • This adds dynamically two properties to the obj – object! • Object is built – in data type • Objects are key value pairs!
  56. Constructor Function • To define a class, define a function

    function Foo() { this.x = 1; this.y = 1; } • var obj = new Foo(); • // Internally a Object is created
  57. this function foo() { // adds prop to global object

    this.prop = 12; } var obj = { method: function() { // goes to obj this.prop = 12; } }; obj.method(); function Dog(name) { // Refers to object being created! this.name = name; this.sayHello = function() { print(this.name + " says hello!"); }; } var dog = new Dog("Spot"); dog.sayHello();
  58. Constructors function Person(name) { this.name = name; } // Should

    be used var jaska = new Person("Jaska"); // Don't! Now this is bound to global object var jeppe = Person("Jeppe");
  59. Better version function Person(name) { // If this refers not

    to Person (for example global object) if(!(this instanceof Person)) { // Let's then use the new word return new Person(name); } else { this.name = name; } } // Now both work var vilma = new Person("Vilma"); var jaska = Person(”Jaska");
  60. "Classes" in EcmaScript 2015 function Point1(x, y) { this.x =

    x; this.y = y; } var origo1 = new Point1(0,0); console.log( origo1.x ); console.log(typeof Point1); class Point2 { constructor(x, y) { this.x = x; this.y = y; } } var origo2 = new Point2(0,0); console.log(origo2.x); console.log(typeof Point2);
  61. You must use the new keyword! class Point { constructor(x,

    y) { this.x = x; this.y = y; } } var origo = new Point(0,0); var fails = Point(0,0);
  62. JSLint • JSLint is JS code quality tool made by

    Douglas Crockford • http://jslint.com • Inspects and warns about potential problems • “Will hurt your feelings” • Excepts that your code is in “strict mode” • Can be used via website or command line (installation required) • Command line tool (Java wrapper for JSLint) • http://code.google.com/p/jslint4java/
  63. JSLint in Command Line • JSLint4java – Java wrapper for

    the JSLint • http://code.google.com/p/jslint4java/ • To use it: • java -jar jslint4java-2.0.5.jar application.js
  64. To enable rhino, node or browser functionality • To enable

    rhino functionality, for example print("") • java -jar jslint4java-2.0.5.jar --rhino application.js • node • java -jar jslint4java-2.0.5.jar –node application.js • browser • java -jar jslint4java-2.0.5.jar --browser application.js
  65. EcmaScript • Goal • Fix “bad” parts of JS while

    maintaining compatible with EcmaScript 5 • Introduces Strict mode • Removes features from the language! Raises errors that were okay in non strict mode • Backward compatible • Add “use strict”, in function or global scope • EcmaScript supports non-strict mode, but it’s depricated!
  66. Strict “mode” • Detection of bad/dangerous programming practices • with()

    statement prevented • Assignment to non-declared variables prevented (i = 3) • Eval is prohibited • Lot of other issues.. • See ES5 specification page 235
  67. Enable strict mode > cat strictmode.js // This is just

    a string, backward compatible! "use strict"; i = 0; > rhino strictmode.js js: uncaught JavaScript runtime exception: ReferenceError: Assignment to undefined "i" in strict mode
  68. Global and local // GLOBAL, everything is strict: "use strict";

    //.. strict program // LOCAL, function is strict function foo() { "use strict"; //.. strict function }