Slide 1

Slide 1 text

JavaScript Development Jussi Pohjolainen

Slide 2

Slide 2 text

Recommended Reading • Recommended reading • JavaScript: The Good Parts by Douglas Crockford • JavaScript: The Definite Guide by David Flanagan • JavaScript Patterns: Stoyan Stefanov • And Google..

Slide 3

Slide 3 text

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)

Slide 4

Slide 4 text

Rise of the Responsive Single Page App Image: http://johnpolacek.github.io/scrolldeck.js/decks/responsive/

Slide 5

Slide 5 text

Mobile is the New Desktop http://ben-evans.com/benedictevans/2015/11/7/mobile-ecosystems-and-the-death-of-pcs

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

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

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

Frontend

Slide 12

Slide 12 text

Intro to Web Standards

Slide 13

Slide 13 text

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).

Slide 14

Slide 14 text

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/

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

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 ..

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

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!

Slide 20

Slide 20 text

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'.

Slide 21

Slide 21 text

Quick intro to JS in Browsers

Slide 22

Slide 22 text

Embed Example

//<![CDATA[ document.write("Hello from JS!"); //]]>

Slide 23

Slide 23 text

External JS Example

Slide 24

Slide 24 text

// event.js function message() { alert("This alert box was called with the onload event"); }

Slide 25

Slide 25 text

Result

Slide 26

Slide 26 text

Exercise

Slide 27

Slide 27 text

EcmaScript

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

Browser Host Objects DOM BOM Image: http://www.daaq.net/old/javascript/index.php?page=the+js+bom

Slide 30

Slide 30 text

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)

Slide 31

Slide 31 text

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)

Slide 32

Slide 32 text

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

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

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

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

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!"); }

Slide 37

Slide 37 text

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

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

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"]

Slide 40

Slide 40 text

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;

Slide 41

Slide 41 text

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

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

Expressions and Operators • Assignment • var x = 5; x++; x += 10; • Comparison • ==, ===, <, >, <=, => ... • Arithmetic • +, /, -, * ... • Logical • &&, ||, !

Slide 44

Slide 44 text

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("");

Slide 45

Slide 45 text

Exercise

Slide 46

Slide 46 text

Functions

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

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) );

Slide 49

Slide 49 text

Function object with arguments function add(a, b) { console.log(arguments); } // { '0': 1, '1': 1 } add(1,1); // null console.log(add.arguments);

Slide 50

Slide 50 text

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

Slide 51

Slide 51 text

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

Slide 52

Slide 52 text

TIP: Avoid Globals by using Func! (function() { var x = "variable"; })()

Slide 53

Slide 53 text

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

Slide 54

Slide 54 text

Functions and Variable Declaring var x = 10; function test() { console.log(x); // outputs what? if(true) { var x = 5; } } test();

Slide 55

Slide 55 text

Variable Hoisting! var x = 10; function test() { var x; console.log(x); // outputs “undefined” if(true) { x = 5; } } test();

Slide 56

Slide 56 text

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();

Slide 57

Slide 57 text

Single Var Pattern function test() { var a = 1, b = 2, …; // rest of the function } test();

Slide 58

Slide 58 text

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();

Slide 59

Slide 59 text

Function Declaration: this works! function testC() { print(foo()); function foo() { return 5; } } <=> function testD() { function foo() { return 5; } print(foo()); }

Slide 60

Slide 60 text

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; } }

Slide 61

Slide 61 text

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();

Slide 62

Slide 62 text

Functions in if-statements function init() { if(true) { function foo() { return 1; } } else { function foo() { return 2; } } return foo(); } print(init()); // 1 or 2?

Slide 63

Slide 63 text

Use this! function init2() { var foo; if(true) { foo = function() { return 1; } } else { foo = function() { return 2; } } return foo(); } print(init2());

Slide 64

Slide 64 text

EcmaScript 2015: default values function test(a = 1) { console.log(a); } test(); test(7);

Slide 65

Slide 65 text

EcmaScript 2015: varargs function test(...values) { console.log(values); console.log(values.length); } test(1, 4); test(1, 4, 7); test(1, 4, 7, 0);

Slide 66

Slide 66 text

Exercise

Slide 67

Slide 67 text

Moving to CLI

Slide 68

Slide 68 text

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

Slide 69

Slide 69 text

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

Slide 70

Slide 70 text

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

Slide 71

Slide 71 text

Exercise

Slide 72

Slide 72 text

OO with JS

Slide 73

Slide 73 text

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

Slide 74

Slide 74 text

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; } }

Slide 75

Slide 75 text

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!

Slide 76

Slide 76 text

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

Slide 77

Slide 77 text

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();

Slide 78

Slide 78 text

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");

Slide 79

Slide 79 text

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");

Slide 80

Slide 80 text

"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);

Slide 81

Slide 81 text

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);

Slide 82

Slide 82 text

Exercise

Slide 83

Slide 83 text

Code Style: JSLint

Slide 84

Slide 84 text

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/

Slide 85

Slide 85 text

No content

Slide 86

Slide 86 text

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

Slide 87

Slide 87 text

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

Slide 88

Slide 88 text

About EcmaScript 5

Slide 89

Slide 89 text

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!

Slide 90

Slide 90 text

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

Slide 91

Slide 91 text

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

Slide 92

Slide 92 text

Global and local // GLOBAL, everything is strict: "use strict"; //.. strict program // LOCAL, function is strict function foo() { "use strict"; //.. strict function }