Maurice Butler
@ButlerMaurice
Meldr / The Locker Project
Patrick Klug
@PatrickKlug
Greenheart Games

Live Backchannel: #dddbrisbane
Source: http://bit.ly/V3nZOO

From professional to beginner in one decision.

  • Preconceived ideas need to be challenged.
    • I thought JavaScript is slow. It isn't.
    • I thought JavaScript is unsophisticated. It isn't.
  • Being a beginner again is frustrating. (especially a CSS beginner)
  • A few things which make it easier
    • a very active community
    • tons of examples
    • tons of libraries
  • HTML/JS is powerful
    • example apps
    • code visually

Where do I start to code?

There is no special entry point. A JS file referenced in HTML is simply executed.

<script src="js/myJSFile.js"><script>
        

Hint: Don't use self-closing tags. It will not work.

<script src="js/myJSFile.js"/> //will not load
        

You could then start coding in the JS file directly.

var a = 5 + 10;
                

But this would place your code into a global scope which is rarely what you want.

Building blocks

A few things you need to get started

//functions
function foo(){
};

foo();

var bar = function(){ //function assigned to a variable
};

bar();

var obj = {};//object
var person = {name:'Patrick'};

var array = [1,2,3]; //array
          

Understanding JavaScript with a C# background

  • Scope
  • Types
  • Truthy and Falsey
  • Functions are objects
  • Hoisting
  • Scope Revisited

Scope - Dont hate me cause im different

  • Scope in JavaScript works very different than scope in C#
  • Javascript uses Function Scope rather than Block Scope
  • But we will come back to that...
Source: http://bit.ly/V3ESJa

Types

JavaScript has only 5 primitive types:

  • boolean
  • string
  • number
  • null
  • undefined

Types

Boolean & String

The JavaScript boolean and string types behave very similarly to their C# counter parts.

There are some minor differences, but they are boring and I wont go into those here.

Types

Number

JavaScript has no float, int, double or any other types to represent numbers

All numbers are represented as a 64-bit floating-point double

The other interesting point is the 2 valid number values NaN and Infinity. The value NaN (stands for Not a Number) occurs when a value is returned as a number type, but the value is not parseable as a number. This is usually when trying to parse a non numeric string value (such as "abc") to a number. The value infinity occurs when a number exceeds the upper limit of the floating point numbers, which is 1.7976931348623157E+10308.

Types

Null

The JavaScript null type is similar to the C# Null however it does have one gotcha.

When applying the typeof operator to a null value, it will return "object". This is actually completely wrong, and is a mistake that was made very early in the language’s standardisation.

It was deemed however that it was too late to fix typeof due to the amount of existing code that would break.

          var x = null;
          console.log(typeof x);  // object
      

Types

Undefined

The JavaScript undefined type is similar to null, however while null means a variable or property has no value, undefined means that the variable or property does not exist.

For a variable it can also mean that the variable was declared but never assigned a value

          var foo;
          console.log(typeof foo); // undefined

          foo = 123;
          console.log(typeof foo); // number

          foo = "abc";
          console.log(typeof foo); // string

          foo = true;
          console.log(typeof foo); // boolean

          foo = null;
          console.log(typeof foo); // object

          foo = {};
          console.log(typeof foo); // object

      

Types

          var foo;
          console.log(typeof foo); // undefined

          foo = 123;
          console.log(typeof foo); // number

          foo = "abc";
          console.log(typeof foo); // string

          foo = true;
          console.log(typeof foo); // boolean

          foo = null;
          console.log(typeof foo); // object

          foo = {};
          console.log(typeof foo); // object
      

Truthy and Falsey

In JavaScript any object can be automatically coerced into a boolean representation (i.e. true or false).

Anything that exists and has a value will evaluate as true unless the value is false, null, undefined, 0, NaN or an empty string.

Truthy and Falsey

        var foo;

        if(foo) // exists but is undefined -> evaluate as false
        {
            console.log(foo); // will not execute
        }

        foo = "Hello World";

        if(foo) // exists and has a value -> evaluate as true
        {
            console.log(foo); // will execute    
        }
      

Truthy and Falsey

We can now use these concepts to write defensive JavaScript, by ensuring variables or properties exist before using them.

        if (someObject && !someObject.foo){
            someObject.foo = 'foo';
        }

        console.log(someObject.foo); 
      

The above code checks if someObject is truthy (not null etc) and if someObject.foo has been defined.

If someObject.foo has not been defined it will set it to the string value ‘foo’ before continuing to log it out.

Functions are objects

A function in JavaScript is an object just like any other object.

While this concept might not be as huge a deal for someone familiar with Generics and Lambda expressions, it is still a big difference between C# and JavaScript.

You can do many more weird and wonderful things

  • Create anonymous functions
  • Assign a function to a variable
  • Pass that variable to another function
  • Change the function object to do other things
  • Parse it as a string
  • And many more

Functions are objects

  • Define a function called foo and then call the named function.

                function foo(){ 
                    console.log('bar');
                }
    
                foo();  // bar
              
  • But how about this?

                var foo = function (){ 
                    console.log('bar');
                }
    
                foo();  // bar
              

Functions are objects

In the second example, we defined an anonymous function and assigned to to the variable foo

We now have a variable foo which we can do what we please with

        console.log(foo); // function (){ 
                          //     console.log('bar');
                          // }

        foo.randomProperty = "We just added a property to an object";

        console.log(foo.randomProperty); // We just added a property to an object
      

Hoisting

When JavaScript is executed, the interpreter moves or “hoists” all variable declarations to the top of their containing function / scope boundary, regardless of where they occur.

        var foo = 'global foo';

        function myFunction() {
            console.log(foo);
        }

        myFunction();

      

This code defines a global variable foo and sets its value to ‘global foo’. We then call my function that logs the value of foo.

Hoisting

Now lets change this function so that it logs the global variable and then logs a local version of foo

        var foo = 'global foo';

        function myFunction() {
            console.log(foo); // undefined
            var foo = 'local foo';
            console.log(foo); // local foo
        }

        myFunction();
      

Why does the first console.log return undefined?

Hoisting

The code that is actually being executed after hoisting has occurred looks like this

        var foo = 'global foo';

        function myFunction() {
            var foo;
            console.log(foo); // undefined
            foo = 'local foo';
            console.log(foo); // local foo
        }

        myFunction();

      

Scope Revisited

OK, time to talk about scope.

In C#, scope is introduced by braces or are "Block Scoped". A variable declared inside a class, function, loop, condition block, etc are available to all members within the blocks braces.

public void Method1()
{
 var elements = new int[] { 0, 1, 2, 3, 4, 5 }; // available everywhere in the function

 for (var i = 0; i < elements.Length; i++)
    {
       var element = elements[i]; // available only within this for loop
         Console.Write(element);
    }
}
      

Scope Revisited

In JavaScript however, functions define scope.

A variable declared outside of a function is in the global namespace. As in any language, you should try to avoid polluting the global namespace.

A variable declared inside a function is visible anywhere within that function but are not visible outside the function.

function Method1(){
  var elements = [0, 1, 2, 3, 4, 5]; // available everywhere in the function
           
  for(var i = 0; i < elements.length; i++) {
    var element = elements[i];  // remember Hoisting? will be available everywhere, 
                                //even though it was originally declared inside the loop
    console.log(element);
  }
}

Scope Revisited

Lets now modify this code to take the the array of values and create an array of functions that return the original values.

        function Method1(){
          var elements = [0, 1, 2, 3, 4, 5],
              functions= [];

          for(var i = 0; i < elements.length; i++) {
            var element = elements[i];
            functions.push(function() {
              console.log(element);
            });
          }

          functions[3]();
        }
      

Scope Revisited

So what is the result of the function call?

        function Method1(){
          var elements = [0, 1, 2, 3, 4, 5],
              functions= [];

          for(var i = 0; i < elements.length; i++) {
            var element = elements[i];
            functions.push(function() {
              console.log(element);
            });
          }

          functions[3]();
        }
      

Scope Revisited

        functions[3]();  // 5
      

As discussed before, JavaScript does not have "Block Scope" thus the for loop has not introduced new scope.

This means that each time the element variable is accessed, the same memory location is updated, rather than a loop iteration specific variable as one would expect in C#

Scope Revisited

For simplicity we will just wrap our for block in an anonymous, auto executing function, (often referred to a closure) and pass the element parameter into this function.

  for (i = 0; i < elements.length; i++) {

      (function (element) {                    // start of closure

          functions.push(
              function() {
                  console.log(element);
              });
          
      }(elements[i]));                         // end of closure
  }
      

Scope Revisited

        functions[3]();  // 3
      

We now log 3 as originally expected.

The code is now similar to the C# example (scope wise) as the element variable is declared, assigned used and destroyed within the for loop.

This is because Hoisting moves variables to the top of a function, the closure stops it bubbling up to the same location as the other variable declarations.

Code Structure

{
    var a = 5;
    var b = a;
}
var b = a; //a does not exist
                        
  • The key to structuring code in JS is scope.
  • Scope is defined by functions.
  • To place your code into its own scope it needs to be enclosed by a function.
(function(){
    var a=5;
    var b=a;//5
})(); //self-executing anonymous function to introduce scope.
var b=a;//undefined
                         

Code Structure 2

  • Self-executing anonymous are used to divide the code base and move things out of the global scope.
  • If you want to define a bunch of functions but you don't need them in global scope, you wrap them in a self-excecuting function.
(function(){
    var foo = function(){
    };
    foo();//available
})();
foo();//unavailable
                        
  • To make this separate code usable elsewhere you just have to attach it to an object in the global scope.
var GlobalObject = {};
(function(){
    var bar = function(){...};
    GlobalObject.foo = function(){
        bar();
    };
})();
GlobalObject.foo();
                    

Code Structure 3

namespace Product
{
  public static class MyStaticClass
  {
    private static int a = 5;
    public static int Foo()
    {
        return a;
    }
  }
}
Product.MyStaticClass.Foo();
                
var Product = {};//simple object serves as a namespace.
Product.MyStaticObject={}; //simple object serves as the container for our static functions
(function(){
    var a = 5;
    Product.MyStaticObject.foo = function(){
        return a;
    }
})();//self-executing anonymous function to introduce scope.
Product.MyStaticObject.foo();
                

Classes 1

There are no classes in JavaScript but there are several features you can use to get similar things.

Option: Use simple objects instead of classes.

  • Objects to simply group some functions and properties.

    var person = {};
    person.name = 'Patrick';
    person.birthday = '15/03/1983';
    person.getAge = function(){};
                    
  • Or the same in JSON-style.

    var person = {
        name:'Patrick',
        birthday:'15/03/1983',
        getAge = function(){
            //logic
        }
    }
                        

Classes 2

Defining a 'class' by using the following facts:

  • 1. A function is an object.
  • 2. You can create a new instance of an object via the new keyword
  • Example:
    var Person = function (name){
        this.name = name;
    };
    var presenter1 = new Person('Maurice');
    var presenter2 = new Person('Patrick');
                        
  • Since a function is an object you could also attach more functions.
    var Person = function (name, birthday){
        this.name = name; this.birthday=birthday;
        this.getAge =function(){
            //logic
        };
    };
    var presenter1 = new Person('Maurice');
    var presenter2 = new Person('Patrick');
                        

Classes 3

My preferred option using the JavaScript prototype object.

var Person = function(name, birthdate){ //think of this as the constructor
    this.name = name;
    this.birthdate = birthdate;
};
(function(){
    //think of this as the class defintion
    var p = Person.prototype;
    p.getAge = function(){
        //logic using this.birthdate;
    };
})(); //scope only available to the class definition

var presenter2 = new Person('Patrick','15/03/1983');
presenter2.getAge();
             

Prototype: The prototype of an object defines the properties and methods which are available on all instances of the object.

C# vs. JavaScript Example

public class Person
{
    public Person (string name, DateTime birthday)
    {
        this.Name = name;
        this.Birthday = birthday;
    }
    //Name and Birthday properties omitted
    public int GetAge()
    {
        //logic
    }
}
var Person = function(name, birthday){
    this.name = name;
    this.birthday = birthday;
};
(function(){
    var p = Person.prototype;
    p.getAge =function(){
        //logic
    };
})();

Advanced Concept: JavaScript inheritance.

Inheriting properties/methods from other objects is also possible in JavaScript.

var DisplayObject = function(x, y){
    this.x = x;
    this.y = y;
};

var Container = function(x, y){
     //roughly equivalent with :base(..) in C#.
    DisplayObject.apply(this, arguments);
};
(function(){
    //this effectively says that any instance of Container
    //should have the same properties/methods as a DisplayObject
    Container.prototype = new DisplayObject();

    //define additional methods/properties for Container objects.
    var p = Container.prototype;
    p.addChild = function(){};
})();

.apply() calls a method with an array of arguments and defines what this is.

arguments holds the arguments passed to a function.

Forging your tool set to suit your C# mind.

  • Dictionary/Hashtable
  • Events
  • LINQ extension methods (mostly IEnumerable<T> methods)
    • .Where() => .filter()
    • .Select() => .map()
    • .Except() => ?
    • .Count(filter) / .Max(filter) / .Sum(filter) / .Average(filter) => ?
    • .FirstOrDefault(filter) / .LastOrDefault(filter) => ?
    • .GroupBy() => ?
  • Other methods I simply got used to
    • .format()
    • ...

My number 1 requirement for a programming language?

Extension methods!

  • I simply re-implemented helper methods by extending the prototype objects.
    Array.prototype.first = function (filter) {
    	if (!filter) {
    		if (this.length > 0)
    			return this[0];
    		return null;
    	}
    
    	for (var i = 0; i < this.length; i++) {
    		var obj = this[i];
    		if (filter(obj))
    			return obj;
    	}
    	return null;
    };
    
    //usage
    [1,2,3,4,5,6].first(function(n){ return n>4; }); //like .FirstOrDefault((n)=>{return n>4;}));
                            

More extension examples

Array.prototype.insertAt = function (index, obj) {
	this.splice(index, 0, obj);
};

Array.prototype.skip = function (count) {
	if (this.length < count)
		return [];
	return this.slice(count, (this.length - count) + 1);
};

//http://stackoverflow.com/a/4673436/10779
String.prototype.format = function () {
	var args = arguments;
	return this.replace(/{(\d+)}/g, function (match, number) {
		return typeof args[number] != 'undefined'
    ? args[number] : match;
	});
};

Number.prototype.clamp = function (min, max) {
	return Math.min(Math.max(this, min), max);
};

Hint: You might want to check for existing functions before overwriting them on prototype objects.

Dictionaries

There is no C# like dictionary in JavaScript but a simple key/value pair holder is easy to come by.

var dict = {}; //use a simple object as a dictionary
dict.myKey = value;
//or like this
dict['stringKey']= value;

//check for value
if (dict.myKey!=undefined){
}
if (dict['stringKey']!=undefined){
}
//access value
dict.myKey;
dict['stringKey'];
              

Dictionaries 2

Iterate over keys

var dict = {};
for (var key in Object.keys(dict)){
}

//or, more often you see this:
for (var key in dict){
    //.hasOwnProperty returns false if the property is from a prototype object.
    if(!dict.hasOwnProperty(key))
        continue;
    var value = dict[key];
}
                

To use a key that is not a string or a number you can use an additional array and use the index as the key.

var keyArray = [obj1, obj2, obj3];
var dict = {};
dict[keyArray.indexOf(obj1)]=value;

if (dict[keyArray.indexOf(obj3)] != undefined){
}
                

Events

It's simple to respond to events from the HTML DOM

<input id="myButton" onclick="UI.onClick()" />
                
var UI = {};
UI.onClick = function(e){
};
                

You can also easily do the same thing from code alone

var myButton = document.getElementById('myButton');
myButton.onclick = function(e){
};
                

But there is no built-in way to define events on your own objects.

Events 2

Events in C# are multicast delegates which essentially means a list of methods which are called when the event fires.

Given this definition we can create our own event implementation:

var EventSource = {};
(function(){
    var p = EventSource.prototype;
    p._events = {}; //dictionary to store event handlers
    p.on = function(key, handler){
        if (this._events[key]==undefined)){
                this._listeners[key]=[];
        }
        this._events[key].push(handler);
    };
    p.off = function(key, handler){
        if (this._events[key]!=undefined && this._events[key].indexOf(handler)!=-1)){
            this._events[key].splice(this._events[key].indexOf(handler), 1); //splice (startIndex, numberToRemove)
        }
    };
    p._raiseEvent = function(key){
        var handlers = this._events[key];
        for (var i=0;i<handlers.length;i++){
            handlers[i]();
        }
    };
})();
                

Events 3

Usage is simple

var MyObject = {};
(function(){
    MyObject.prototype = new EventSource(); //inherit methods/properties from EventSource
    var p = MyObject.prototype;
    p.doSomething = function(){
        this._raiseEvent('somethinghappened');
    };
})();
//somewhere else
instance.on('somethinghappened',function(){
    //handler
});
                

Common pitfalls

Usage of this

var allPresenters = [
	{ id: 0, name: 'Maurice', talks: [0, 2] },
	{ id: 1, name: 'Patrick', talks: [0, 3] }
];
var DDDTalk = function (talkId, name) {
	this.talkId = talkId; this.name = name;
};
(function () {
	var p = DDDTalk.prototype;
	p.getPresenters = function (arr) {
		return arr.filter(function (item) {
			return item.talks.indexOf(this.talkId) != -1;
		});
	};
})();
    var talk = new DDDTalk(0, 'JavaScript for C# devs');
    var presenters = talk.getPresenters(allPresenters);
}
            

Common pitfalls (this)

Simple solution

(function () {
	var p = DDDTalk.prototype;
	p.getPresenters = function (arr) {
            var id = this.talkId;
		return arr.filter(function (item) {
			return item.talks.indexOf(id) != -1;
		});
	};
})();
                    
(function () {
	var p = DDDTalk.prototype;
	p.getPresenters = function (arr) {
            var that = this;
		return arr.filter(function (item) {
			return item.talks.indexOf(that.talkId) != -1;
		});
	};
})();
                    

Common pitfalls

  • this might not be what you think it is. just keep it in mind when things don't work.
  • When working with functions/callbacks and variables in for loops, be aware of scope issues.
    • You will likely go half insane because of this at least once.
    • Just keep calm. Re-read Maurice's blog post and earn the padawan achievement again.
    • I did it thrice :)
  • typos, syntax errors etc.
    • just be more careful. test early, test often.
    • and use
      'use strict';
      in Visual Studio 2012
  • be careful when using
    if (value)
    to check if a value is set as this will be false if the value is 0. you can use if (value!=undefined) instead.

My Recommendations (Patrick)

  • Start with a goal in mind.
  • Start coding.
  • Read code.
  • Read more code.
  • Leave 'architecture' frameworks for later. (You might not need MVVM)
  • Learn jQuery (esp. if you need to do a lot of DOM manipulation).
  • If something is not working: Keep calm and investigate.
  • If you don't understand why your own code is working, you should not continue.
    • Don't be the superstitious dev.
  • Read Maurice's blog post on hoisting and scope.

Thanks!

Maurice Butler
@ButlerMaurice
Meldr / The Locker Project
Patrick Klug
@PatrickKlug
Greenheart Games

Live Backchannel: #dddbrisbane