MSSE SENG 5199

Course Materials for the MSSE Web Application Development Course

Javascript and TypeScript

Mike Calvo

mike@citronellasoftware.com


Javascript


Language Features


Example Syntax: Variables

var x;
var y = 2;

x = 3.4;
x = false;

y = 'dynamic... ohhh.';
y = "Strings can be single or double quoted";

console.log("This is Javascript's version of println");

Conditions, Arrays and Loops

var a = [1, 2, 3, 4, 5];

var sum = 0;
for (var i = 0; i < a.length; i++) {
  if (a[i] % 2) {
    sum += a[i];
  }
}
console.log('sum = '+sum);


JavaScript Functions Syntax


Example Function Syntax

function print(parameter) {
  console.log('parameter = '+parameter);
}
print('yo');

// Optional function name assists debugging
var log = function log(words) {
  console.log('logging: '+words);
};

var forEach = function(array, fn) {
  for (var i = 0; i < array.length; i++) {
    fn(array[i]);
  }
};

forEach(['one', 'two', 'three'], log);


Objects


Object Examples

var emptyObject = {};
var person = { name: 'Mike', email: 'mjcalvo@gmail.com'};
console.log('Name: '+person.name);
console.log('Email: '+person.email);

person.address = { street: '123 Main', city: 'Lexington' };

console.log('City: '+person.address.city);

person['address']['city'] = 'London';

person.zip // !!! undefined !!!

What are Prototypes?


Example Javascript Inheritance

var person = { name: 'Mike', age: 43 };
person.speak = function(words) { console.log('speaking: '+words); };

var employee = Object.create(person)
employee.work = function() { this.speak("I'm working..."); };

employee.work();

Javascript Reflection

typeof 3           // 'number'
typeof 'status'    // 'string'
typeof {}          // 'object'
typeof {}.name     // 'undefined'
typeof {}.toString // 'function'

var obj = {name: 'name', count: 3};
obj.hasOwnProperty('name') // true
obj.hasOwnProperty('color') // false

Looping Over Properties

var object = { name: 'a', date: new Date(), scores: [1, 2, 3] };
for (var p in object) {
  if (object.hasOwnProperty(p)) {
    console.log(p+': '+object[p]);
  }
}

Deleting Properties

var object = [name: 'Mike', type: 'employee'];
delete object.type; // Now object == [name: 'Mike']

var array = ['a', 'b', 'c'];
delete array[1]; // ['a', undefined, 'c']

Method Invocation Model

var obj = {
  name: 'Billy',
  go: function() {
    this.name += ' going... ';
  }
};

Plain Function Invocation

var obj = {
  go: function() {
    var that  = this;

    var helper = function() {
      that.value = 'nice hack!';
    }

    helper();
  }
};

Constructor Invocation


Example Constructor

var Person = function(name) {
  this.name = name;
}
Person.prototype.get_name = function() { return this.name; };

new Person('John').get_name();


Apply Invocation


Apply Example

var add = function(a, b) {
  return a + b;
};

add.apply(null, [5, 6]);


Arguments


Arguments Example

var addAll = function() {
  var sum = 0;
  for (var i = 0; i < arguments.length; i++) {
    sum += arguments[i];
  }

  return sum;
}

addAll(2, 5, 6, 7, 10, 22);


Augmenting Types

String.prototype['trim'] = function() {
  // use a regular expression to remove whitespace
  return this.replace(/^\s+|\s+$/g, '');
};
"   hello    ".trim();

Global Scope


Function To Protect Scope

var object = (function() {
  var value = 5;  // Shhhh - this is private

  return {
    increment: function(amount) { value += amount; },
    getValue: function() { return value; }
  }
})();

object.increment(10);
object.getValue();
object.value; // !!! Undefined !!!

Callbacks


Callback Example

sendMyRequest(url, function(status) {
  console.log('Request completed.  Status: '+status);
});

Regular Expressions


RegEx Example

var parse_number = /^-?\d+(?:\.\d*)?(?:e[+\-]?\d+)?$/i

parse_number.test('1');           // true
parse_number.test('98.6');        // true
parse_number.test('123.45E-67');  // true
parse_number.test('192.168.1.1'); // false


JavaScript in HTML


Example HTML Scripts

<!DOCTYPE html>
<html><head>
  <script src="angular.js"></script>
  <script>
    var app = {};
  </script>
  </head>
  <body>
    <script>
      document.body.innerHTML += '<div>hi</div>';
    </script>
  </body>
</html>

Excellent JavaScript Books


Typescript


Typescript is a Transpiler


Features


Optional typing


Basic TypeScript types


Type Assertions

let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
let anotherLength: number = (someValue as string).length;

Defining types

let greeting : string;
function sum(x : number, y : number) : number {
  return x + y;
};

Type inference

function sum(x, y : number) : number {
  return x + y;
};

Interfaces


Interface Example


interface Person {
  firstName: string;
  middleName?: string;
  lastName: string;
  readonly age: number;
}

function greeter(person: Person) {
  return "Hello, "+person.firstName+" "+person.lastName;
}

document.body.innerHTML = greeter({firstName: 'Joe', lastName: 'Smith'});

Function Type Example

interface SearchFunc {
    (source: string, subString: string): boolean;
}

let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
    let result = source.search(subString);
    return result > -1;
}

TypeScript Classes


Class Example

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");

Class Accessors

class Employee {
    private _fullName: string;
    public passcode

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode == 'let me in')
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

Modules


#Example Modules greet.ts:

export function sayHello(name: string) {
    return `Hello from ${name}`;
}

main.ts:

import { sayHello } from "./greet";

console.log(sayHello("TypeScript"));

#Example Default Export

JQuery.ts

declare let $: JQuery;
export default $;

App.ts

import $ from "JQuery";
$("button.continue").html( "Next Step..." );

Let, Var and Const


Spread Operator

let first = [1, 2];
let second = [3, 4];
let bothPlus = [0, ...first, ...second, 5];
// bothPlus = [0, 1, 2, 3, 4, 5]