Should I use Typescript


Typescript is a stone’s throw from 1.0 today. Here are the answers I need to make my decision:

  1. How to use it with AngularJS
    2. Is typescript open source ?
      1. Yes :
      2. typescript for windows 8 apps
        3. vs Traceur
        4. Does it work for node apps
          1. npm install -g typescript
          2. Will it help me learn ES6
            1. Yes, coz for debugging I’ll be looking at JS code and so will have to understand what TS code compiles to what JS and how and why


Set the “Generate Source Map” to True in the Visual Studio options to create source maps between TypeScript and JavaScript to enable TypeScript debugging. This option applies the –sourcemap compiler switch, which in turn creates the maps at compile time.

The TypeScript compiler by default compiles to ECMAScript 3 (ES3)-compliant code; however, you can compile to ECMAScript 5 (ES5) if you change the “Compile to ECMAScript 3” option to False in Visual Studio, which sets the tsc compiler flag –target to generate ES5 code. Developers who want to use property-style syntax or any ES5 or proposed ES6 TypeScript features should set this switch.


I’m ready to start now. Off to:

Egghead Angular


  1. $scope is not model, just the ref to stuff in the div of controller
  2. Ng-model inside ng-app but not in any controller is part of $rootScope
  3. Svc define with Svc case
  4. myApp.factory(‘Data’, function() {

return(message: “Hello”); }

function myCtrl($scope, Data) {

$scope.Data = Data;


  1. In svc always pass the data as taking it from scope is not ideal for reusabilty
  2. Convert Svc to Filter whenever needed and simply put the svc code in A

Here: myApp.filter (‘reverse’, function() {a})

  1. Use inbuild filters like Filter and OrderBy
    1. Filter: $ for all
    2. orderBy:’-name’
    3. limitTo:5 or -5
    5. Lowercase
    6. Use the JQLite features like element.bind(“mouseenter”) etc.
    7. Create Directive Behaviors for events etc
    9. USE SCOPE.$APPLY(“FUNCTION NAME”) AND IN THE DIR DECLERATION <div myDirective=”deleteTweets()”>, this string will go In attr of the dir and apply: scope.$apply(attr.mydirective)
    10. U can define the controller within the directive also
    11. When sharing data b/w directives, the parent can act as API and expose functions, But note that u should create scope of parent as Isolate using scope: {} so that child can’’t override it.
    12. But if u do scope: {}, then it will not be shared with the controller of this dir as well. For that,  in dir do done: choredone() and in scope say done:”&” //meaning expression ie u can say: done = “logChore(chore)” and then ng-clk= “done({chore:chore})”

Learning Javascript




  1. 1.       undefined and null

Somewhat unnecessarily, JavaScript has two “non-values”: undefined and null.

  • undefined means “no value”. Uninitialized variables are undefined:
  •     > var foo;
  •     > foo
  •     undefined

If you read a non-existant property, you also get undefined:

> var obj = {}; // empty object



Missing parameters are undefined, too:

> function f(x) { return x }

> f()


  • null means “no object”. It is used as a non-value when an object is expected (parameters, last in a chain of objects, etc.).

Normally, you should treat undefined and null equivalently, as if they were the same non-value. One way of checking for them is via an explicit comparison:



Another way is to exploit the fact that both undefined and null are considered false:

    if (!x) {



Warning: false, 0, NaN and ” are also considered false.


  1. primitives have no types you can access in the language, so each primitive type has an associated type, a so-called wrapper type:
  • The wrapper type of booleans is Boolean. Booleans get their methods fromBoolean.prototype:


  1. Objects are Mutable, Primitives are not
  2. There are two operators for categorizing values: typeof is mainly used for primitive values, instanceof is used for objects.

typeof looks like this:   typeof «value»

  • The type of a function is ‘function’ and not ‘object’. Given that Function(the type of functions) is a subtype of Object (the type of objects), this isn’t wrong.
  • The type of null is ‘object’. This is a bug, but one that can’t be fixed, because it would break existing code.
  1. instanceof looks like this:

«value» instanceof «Constr»

It returns true if value is an object that has been created by the constructor Constr (think: class). Examples:


> b instanceof Bar


> {} instanceof Object


> [] instanceof Array


> [] instanceof Object  // Array is a subtype of Object


  1. The following values are interpreted as false:

undefined, null

Boolean: false

Number: -0, NaN

String: ”

All other values are considered true. Values interpreted as false are called falsy, values interpreted as true are called truthy.

  1. Binary logical operators

Binary logical operators in JavaScript are short-circuiting – if the first operand suffices for determining the result, the second operand is not evaluated. For example, in the following code, the function foo() is never called.

false && foo()

true  || foo()

Furthermore, binary logical operators return either one of their operands – which may or may not be a boolean. A check for truthiness is used to determine which one:

And: If the first operand is falsy, return it. Otherwise, return the second operand.

> NaN && ‘abc’


> 123 && ‘abc’


Or: If the first operand is truthy, return it. Otherwise, return the second operand.

> ‘abc’ || 123


> ” || 123


  1. 8.       Equality operators

To check equality in JavaScript, you can either use strict equality (===) and strict inequality (!==). Or you can use lenient equality (==) and lenient inequality (!=). Rule of thumb: Always use the strict operators, pretend that the lenient operators don’t exist.

NOTE: === is compare by ref, so a===a is true

  1. JS has packing and unpacking of Primitives to give them utilities

10. Number(false): returns 0 AND IS USED FOR EXPLICIT CASTING

  2. Strings are concatenated via the plus (+) operator, which converts the other operand to string if one of the operands is a string.
  4. In all loops:
    1. break leaves the loop.
    2. continue starts a new loop iteration.
    3. function declaration:

function add(param1, param2) {

return param1 + param2;


Function expression:

var add = function (param1, param2) {

return param1 + param2;


  1. Function declarations are hoisted, moved in their entirety to the beginning of the current scope. That allows you to refer to functions that are declared later:

function foo() {

bar();  // OK, bar is hoisted

function bar() {



Note that while var declarations are also hoisted, assignments performed by them are not:

function foo() {


var bar = function () {

// …



  1. all parameters available via the special variable arguments. arguments looks like an array, but has none of the array methods.
  2. common pattern for assigning default values to parameters:

function pair(x, y) {

x = x || 0;  // (*)

y = y || 0;

return [ x, y ];


  1. Converting arguments to an array

function toArray(arrayLikeObject) {

return [];


  1. Exceptions

function throwException() {

throw new Error(‘Problem!’);



try {


} catch (e) {

console.log(e);  // Error: Problem!

console.log(e.stack);  // non-standard, but often supported


  1. Strict


‘use strict’;

You can also switch on strict mode per function, by putting the above code at the beginning of a function:

function functionInStrictMode() {

‘use strict’;



  1. Explicit errors
  2. this in non-method functions is UNDEFINED. In non-strict mode, the value of this is the so-called global object (window in browsers)
  3. No auto-created global variables
  4. 22.   Due to hoisting (see below), it is usually best to declare variables at the beginning of a function
  5. 23.   Variables are function-scoped: The scope of a variable is always the complete function (as opposed to the current block).
  6. Variables are hoisted: Variable declarations are hoisted: The declaration is moved to the beginning of the function, but assignments that it makes stay put
  7. Closures: Each function stays connected to the variables of the functions that surround it, even after it leaves the scope it was created in. A closure is a function plus the connection to the variables of its surrounding scopes. What createIncrementor() returns is thus a closure.
  8. IIFE: Simulating block scoping

Sometimes you want to simulate a block, for example to keep a variable from becoming global. The pattern for doing so is called IIFE (Immediately Invoked Function Expression):

(function () {  // open block

var tmp = …;  // not a global variable

}());  // close block

Above, you can see a function expression that is called right away. The parentheses prevent that it is interpreted as a function declaration; only function expressions can be immediately invoked. The function body introduces a new scope and prevents tmp from becoming global.

  1. Inadvertent sharing via closures

The following is a niche problem, but it can bite you hard if you are not aware of it. Thus, feel free to skim, it is enough to get a rough impression of what is going on.



var result = [];


result.push(function () { return i });  // (*)




The value returned in line (*) is always the current value of i, not the value it had when the function was created. After the loop is finished, i has the value 5, which is why all functions in the array return that value. If you want a snapshot of the current value, you can use an IIFE:


(function (i2) {

result.push(function () { return i2 });

}(i));  // copy current i


  1. Like all values, objects have properties. You could, in fact, consider an object to be a set of properties, where each property is a (key, value) pair. The key is a string, the value is any JavaScript value. So far, we have only seen properties whose keys were identifiers, because those are the only keys that the dot operator can handle. In this section, you’ll learn an additional way of accessing properties that can handle arbitrary strings as keys.
    1. a.       Single objects

In JavaScript, you can directly create objects, via object literals:

var jane = {

name: ‘Jane’,


describe: function () {

‘use strict’;

return ‘Person named ‘;




The in operator checks whether a property exists:

    > ‘newProperty’ in jane


    > jane.newProperty !== undefined

The delete operator removes a property:

    > delete jane.newProperty


  1. b.      Arbitrary property keys

A property key can be any string. So far, we have seen property keys in object literals and after the dot operator. (Roughly) you can only use them that way if they are identifiers. If you want to use other strings as keys, you have to quote them in an object literal and use square brackets to get and set the property:

var obj = { ‘not an identifier’: 123 };

    > obj[‘not an identifier’]



    > var x = ‘name’;

    > jane[x]


    > jane[‘na’+’me’]


  1. 29.   Extracting methods

If you extract a method, it loses its connection with the object. On its own, the function is not a method, any more and this has the value undefined (in strict mode).

> var func = jane.describe;

> func()

TypeError: Cannot read property ‘name’ of undefined


> var func2 = jane.describe.bind(jane);

> func2()

‘Person named Jane’

  1. Functions inside a method

Every function has the special variable this. This is inconvenient if you nest a function inside a method, because you can’t access the method’s this from the function.

Fix #1: store this in a different variable.

logHiToFriends: function () {

‘use strict’;

var that = this;

this.friends.forEach(function (friend) {

console.log(’ says hi to ‘+friend);



Fix #2: forEach has a second parameter that allows you to provide a value for this.

logHiToFriends: function () {

‘use strict’;

this.friends.forEach(function (friend) {

console.log(’ says hi to ‘+friend);

        }, this);



  1. 31.   Constructors: factories for objectssd

In addition to being “real” functions and methods, functions play a third role in JavaScript: They become constructors, factories for objects, if invoked via the new operator. Constructors are thus a rough analog to classes in other languages. By convention, the names of constructors start with capital letters. Example:


// Set up instance data

function Point(x, y) {

this.x = x;

this.y = y;


// Methods

Point.prototype.dist = function () {

return Math.sqrt(this.x*this.x + this.y*this.y);


We can see that a constructor has two parts: First, the function Point sets up the instance data. Second, the property Point.prototype contains an object with the methods. The former data is specific to each instance, the latter data is shared between all instances.

To use Point, we invoke it via the new operator:


> var p = new Point(3, 5);

> p.x


> p.dist()


p is an instance of Point:

> p instanceof Point


> typeof p


  1. Read: The pitfalls of using objects as maps in JavaScript
  2. Property length always indicates how many elements an array has. But it can also be used to remove trailing elements from the array:

> arr.length = 2;

The in operator works for arrays, too.

> 1 in arr // does arr have an element at index 1?

Note that arrays are objects and can thus have object properties:

> = 123;

> or arr[‘foo’]


TypeOf Array is object

arr.pop()  // remove last element

arr.shift()  // remove first element


arr.unshift(‘x’)  // prepend an element

arr.push(‘x’)  // append an element


arr.slice(1, 2)  // copy elements


arr.indexOf(‘b’)  // find the index of an element


arr.join(‘-‘)  // all elements in a single string


    > arr.join(”)


    > arr.join()



  1. 34.   Iterating over arrays

There are several array methods for iterating over elements. The two most important ones areforEach and map.



[ ‘a’, ‘b’, ‘c’ ].forEach(

function (elem, index) {  // (*)

console.log(index + ‘. ‘ + elem);


map creates a new array, by applying a function to each element of an existing array.



[ 1, 4, 9 ]


  1. Regular expressions

JavaScript has built-in support for regular expressions. They are delimited by slashes:



Method test(): is there a match?

> /^a+b+$/.test(‘aaab’)


> /^a+b+$/.test(‘aaa’)


Method exec(): match and capture groups

> /a(b+)a/.exec(‘_abbba_aba_’)

[ ‘abbba’, ‘bbb’ ]


  1. Math is an object with arithmetic functions. Examples:

> Math.abs(-2)


  1. Other functionality of the standard library

JavaScript’s standard library is relatively Spartan, but there are more things you can use:


JSON: an object with functions for parsing and generating JSON data.

console.* methods: these browser-specific methods are not part of the language proper, but some of them also work on Node.js.

  1. Calling Primitive Wrapper Constructors Without new Returns Primitive Values

The primitive string, number, and boolean values can be created by invoking the corresponding constructor function without the new keyword.

//logs true

console.log(String(‘foo’) === ‘foo’);

console.log(Number(5) === 5);

console.log(Boolean(‘true’) === true);


//logs false because using new created Object wrapper

console.log(new String(‘foo’) === ‘foo’);


console.log(new Boolean(‘true’) === true);



  1. Changing Parameter Value Does Not Change Argument Value

If you change the value of a parameter, it does not effect the argument. For instance, if you pass an array argument into a function, then change the value of the parameter, the array argument does not change its reference.

  1. //use Object() to create primitve number wrapper object

console.log(Object(1) instanceof Number); //logs true


//use Object() to create primitve string wrapper object

console.log(Object(‘foo’) instanceof String);


//use Object() to create primitve boolean wrapper object

console.log(Object(true) instanceof Boolean);

  1. Delete Won’t Delete Inherited Properties
    1. 42.              String Wrapper Objects Are Array-like

Because string wrapper objects create an array-like object (e.g. console.log(new String(‘foo’)); //logs foo {0=”f”, 1=”o”, 2=”o”}) we can use an index to access individual characters in a string (fyi >ie7).

  1. Accessing Properties From Primitive Numbers
    1. The first . after a primitive number is parsed by JavaScript as a floating point literal. To gain access to object properties on a number wrapper object you can do the following:
    2. //use braket notation
    3. console.log(2[‘toString’]()); //logs 2
    4. //use dot notation after accounting for floating point
    5. console.log(2..toString()); //logs 2
    6. //use brakets
    7. console.log((2).toString()); //logs 2


43. When To Use null And When Not To Use undefined

Simply stated, null is the value for nothing, while undefined is the lack of a value. It is common practice for a developer to only make use of the null value when needing to indicate no value as of yet, and leave undefined for JavaScript to use indicating a total lack of value. By using null in your program you can differentiate between JavaScript telling you a value is missing and you reminding yourself that you have not yet provided a value.


Placement Of ++ and — Operators

If the placement of ++/– operators comes after a variable (i.e. boo++) then the value returned is the value previous to incrementing/decrementing. If the placement of ++/– operator comes before a variable (i.e. ++foo) then the value is incremented/decremented and this new value is returned.