JavaScript The Good Things to Know

Null and array

The type null or the type array are in fact of type object. You can verify this by using typeof.

console.log(typeof(null));
console.log(typeof([1,2,3]);

Variables Name

Variables name can have illegal character if used with quote when defined. For example, you can use numeric and alphanumeric character with underscore but you cannot use directly a dash for example. The variable name this-is-illegal is not legal but if you define your object with the property name “this-is-illegal” it works.

var yourObject = {
  "this-is-illegal":"but it works because of the quote",
  this_is_legal : "and does not require quote"
};

Even if the illegal character can be by-passed by the first approach, using quote, it is not recommended to write you code this way. Retreving the value require to use the array notation instead of the dot notation.

var v1 = yourObject["this-is-illegal"];
//instead of 
var v1 = yourObject.this_is_legal;

arguments variable

Every function can access the arguments keyword. This variable is not an official JavaScript array (lack of Array method) but can access every elements with the square bracket.

function add(a,b)
{
   return a + b;
   // or
   return arguments[0] + arguments[1];
}

But this goes far beyond that. You can define your function to not have any arguments and use it with multiple arguments. The arguments variable will hold all arguments passed to the function and not only those officially specified.

function add()
{
    var index
    var sum = 0;     
    for (index = 0; index < arguments.length; index += 1) 
    {         
       sum += arguments[index];     
    }     
    return sum
}
var result = add(1,2,3,4,5); // 15

Default Initialization

If you are not sure if a variable has already been initialized you can use the || operator to check and assign.

var variableWithValueForSure = anotherVariable.variable1 || "defaultValue";

What it does is that it check if the first expression returns undefined. If it is undefined, than this one return false. Since it returns false, the next expression is evaluate which set the value. In the case it is not undefined, this one return not true but the value directly. This is why, often in JavaScript we see the same variable doing this trick to itself to be sure that it is defined. The next example ensures that the variable “me” is defined and not undefined.

var me = me || {};

Object and Dynamic Variables

It is possible to add variables at anytime with JavaScript. You just need to set a value to have the variable defined inside your object. This is also true for functions.

var obj = {
   variable1 : 1
};
obj.newVariable = 2; //newVariable is added to the object obj

References is used not copy

Every time you set an existing object to another variable this one pass its reference. This is true for function parameters but also for variable inside a function.

var x1 = x2; //x1 and x2 are the same now
x2.v1 = 'value1';
//x1.v1 is also at 'value1'

Prototype

Prototype is the concept in JavaScript that allow you to share information through different object of the same type. When calling a function or variable on an object, if this one does not find the function or variable it go check if it can find it in its prototype. If it does not find it it goes to the prototype of the prototype and so on until it reach object.prototype. If nothing is found, it return undefined.

hasOwnProperty

If you want to loop your object proprety (variables and functions) than you will stumble into prototype properties which you may not want to see. If you want to see only method that you have defined for the object and not those ones from the prototype you must use the function hasOwnProperty(‘propertyToCheck’).

var propertyName ; 
for (propertyName in yourObject) 
{     
    if (yourObject.hasOwnProperty(propertyName])) 
    {
          //Do what you want with the property that is inside YourObject and not inside the its prototype     
    } 
}

We used the for in statement to loop through all properties. This give us property in an non-specific order. If you want to have properties in the order defined in the code you must use a for with a integer that loop every properties in an array.

Delete keyword

Using delete can remove a property. For example, if you define a property named “prop1” and you execute delete on it, this one will return undefined exepted if the prototype has a “prop1” method. Because of the nature of the prototyoe

Adding Method to Prototype

You can add methods to an object with the prototype. You just need to use the prototype keyword after the type you want to enhance. The example below add a trim method to any string.

String.prototype['trim'] = function () 
                       {     
                            return this.replace(/^\s+|\s+$/g, ''); 
                       };
This add the trim method to all String type.

Variables Declaration

In JavaScript it is better to define variable in the beginning of the function instead of the best practice that suggest to declare the variable the nearest of its use. The reason is that JavaScript scope works differently than other languages. JavaScript variables defined in a scope can access others variables outside its scopes.

var Program = function()
{
  var var1 = 1;
  var Program2= function()
  {
    var1 = var1 + 1; // This can access var1 function which is not the case in other scoped language.
  }
  Program2(); // Call f2 function
  //The value of var 1 is 2;
}

For example, this does not work in C#:

class Program
{
        private int a;

        private class Program2
        {
            public Program2()
            {
                a = a + 1; // Do not compile
            }
        }
}

Apply Keyword

You can call any function with by following this function with the method apply. This one takes two parameters. The first one is the value you want to set to this for the method you call. The value can be set to null if you do not want to pass a value to the this of the function. The second parameter is an array. This array are converted into the function parameter.

function add(a,b)
{
   return a + b;
}
//Can be called this way:
var result1 = add(1,2); //3
//or
var result2 = add.apply(null,[1,2]); //3

Exceptions

You can throw exception and catch them. The exception throw an object you want. You can use any thing.

throw {name: 'Error Name', message : 'message you want'};

Thrown statement are read by catch block. If you want to catch multiple exception, than you must do a if statement on a property you want, for example the name.

try
{
    throw {name: 'StackOverFlow', message : 'message you want'};
}
catch(e)
{
    if(e.name === 'StackOverFlow')
    {
        console.log('***' + e.name + ': ' + e.message + '***');
    }
    console.log(e.name + ': ' + e.message);
}

Chaining Calls

It is always good to return the this keyword if your method return nothing. This allow to do chaining calls.

var Human= function() {
  this.name = 'Not Defined';
  this.gender = 'm';
};

Human.prototype.setName = function(name) {
  this.name = name;
  return this;
};

Human.prototype.setGender = function(gender) {
  this.gender = gender;
  return this;
};

This allow us to chain because every function return the this reference.

var patrick = new Humain()
                  .setName('patrick')
                  .setGender('male');

Javascript Encapsulation with Closure

JavaScript provides Encapsulation with something named Closure. Since everything in JavaScript uses function, this one too. The principle of closure is to encapsulate every variables and methods into a cohesive function. This allow us to scope what is private to the object from what is public. It is very similar to object oriented class. Private methods and variables are not returned by the closure while public methods and variable are. Let’s start with an example to demystify the concept of closure.

var referenceToTheObject = (function () 
{     
	var privateVariable = 0;     
	return 
	{         
		 publicMethod1: function () {       }
		,publicMethod2: function () {       }     
	}; 
}()
);

This is interesting because in fact, we are invoking an anonymous function (see the line before the last one). This function return an object with two public functions. As you must know now, these function can call any methods and variables in their outer scope. This mean that both public method can call each others but also the private variable. The private variable is not reachable outside the anonymous function because it is not returned by the anonymous function.

Developing with IIS Express to Full IIS

Developing with IIS Express has its limitation. More you are developing and more you may have several website, web api, WCF and others system that must run together. You can increase your compilation process by only compiling and publishing the system that has changed. Visual Studio is bright enough to not recompile every libraries but it also has it pitfalls with IIS Express that suddenly have some of its references not synchronize. The result is obvious. First of all, the “start up” project will work but some of the others will not. For example, if you have a web project and a web api with the web as a startup project, you may have the web working when the web api will result to any types of error possibles.

A solution is to use IIS instead of IIS Express. This way, every compilation, only the libraries that has changed are compiled but once it is compiled, all your system will stay in a working stage (indeed it must have been in a working stage). To switch is pretty easy. Open IIS and create one website for your web project and so on. Define different ports for all your website and that’s it. Not so fast! You can have a error 500:

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default.

Error500ConfigurationSectionFail

This error occurs if you have not added some of IIS features. To add those features, open the Windows Feature by typing “Turn Windows features on or off” in the start menu. This open a window with some Windows feature. Select “Internet Information Services”, “World Wide Web Services” and all of them.

IISFeaturesEnabled

From there, be sure that your web application in IIS point to the web project and the other one to the web api project. Not the DLL folder, but the folder where the project is located. You just need to compile and you are up and running. If you need to debug with break point, you need to go in Visual Studio and go to Debug > Attach To Process. Click “Show Process from all user” and select the w3wp.exe process. Click attach and you are ready to debug.

How To Delay Some of your Web Resource

If you are working with JavaScript and Asynchronous Module Definition (AMD) you know that you have the possibility to have module that depend on others. At some point, you may want to test what would happen if one of your script takes a lot of time to load. For example, if you have a JavaScript module named “A” that depends on “B” and “C” and only when “A” is loaded can execute a task, you may want to test if the task required is really trigged when both dependencies are loaded.

To be able to test that you can use Fiddler. Fiddler let’s you see all Http traffic but it can also let you play with responses. To do, open the AutoResponse tab.
FiddleAutoResponse

You need to set up for the URL you want a response action. You can use an exact math, a file name or use any Regex you want. When the url comparison is true by one of your matches than the respond is launched. For us, adding a delay is done by adding the following command *delay:#### followed by the number of millisecond to have the delay.

*delay:5000

During your test, the code that must be executed after both dependencies load will be delayed if you have setup a delay for one or many of the dependencies.

TypeScript Hashmap Equivalence in JavaScript

TypeScript is transformed into JavaScript and sometime you start some of your code into TypeScript and finish into JavaScript. This is a scenario that you can see when developing some code in TypeScript and at some point is integrated into some existing JavaScript code.

TypeScript allows to have hash map in which you define the type for your key and for the value that it will hold. Let’s take the example of a hash map that has a string key and a string value.

var arr = { [path:string]:string; }; //Hashmap that has for key a string and for value a string

If you need to use this variable in JavaScript and be sure that it will continue to work when coming back into some JavaScript generated by TypeScript you have to keep in mind that this is in fact a double array. If you want to define some values for this variable, you must define for each key a property that contains an array of value. For example imagine two keys with two values each like the example below.

var arr = {'k1':['p1','p2'],'k2':['2p1','2p2']}

This is a working example that can be read back in TypeScript. It is also possible with JavaScript to get back all information by looping through all the keys and values even if the k1 and k2 of the previous example are properties.

for (var key in arr) {
   var allValues = arr[key];
   for (var keyValue in allValues) {
	console.log('Key ' + key + ' has value : ' + allValues[keyValue]);
   }
}

QUnit A JavaScript Unit Test Framework

QUnit is a unit testing framework developed by JQuery Team. It is available at http://qunitjs.com/ but can be found also if you go to JQuery website and click the last button of the header toolbar. The framework has assertion methods that you are used to use with Java or C# but also a webpage that has all your tests status displayed in a clean way. This is interesting to have the big picture of your test suites health.
QUnit

To start testing, you need to create a Html page that refer the .css and the .js file of the QUnit Framework. The last required action that you must do before coding your test is to define in the html two places holders. One must have the id qunit and the other one qunit-fixture. The first one contains all your unit tests and unit test result. The second one is used to insert Html that your test can test against it.

<div id="qunit"></div>
<div id="qunit-fixture"></div>

Here is the result of a falling test.
qunit-example

In a nutshell, Qunit provides some method to organize your test, to compare values, to test your assertion expectation and to test exceptions.

To organize your test into categories, you must call the module method. At its simplest expression, only a name can be defined. Otherwise, you can specify some lifecycle methods. One method before each tests of your category and one method after each tests of your category.

QUnit.module('Category of test'); // Create a group of test

QUnit specify each test within the method test. The first parameter is the name of your test, the second is a function that contains your test.

QUnit.test('This is test 1', function(){
//Test goes here
});

The function can use several methods of assertion and expectation. The first one is the equal method. This is the same as any equal method of any other unit testing framework. You do not have to provide a third parameter for the message, this one is optional. It is also possible to use notEqual method to compare something that should not be equal to a specific value. These method use the double equal and if you need something more robust, like your would do with the triple equal than you must use the strictEqual.

QUnit.equal('x','x'); // Assert a value
QUnit.equal('x','y', 'X and Y are not equal and it must be'); // Assert a value
QUnit.notEqual('x','z', 'X and Z are equal and must not'); // Assert a value
QUnit.strictEqual( 1, 1, "1 and 1 have the same value and type");
QUnit.notStrictEqual( 1, "1", "1 and '1' are not the same");

As you see, we are using the QUnit on every assertion calls. In fact, you can use a shorter version by using the parameter of the testing function.

QUnit.test('This is test 1', function(q){
    q.equal(...);
});

Another primitive assertion is to test against a boolean. This can be done with the ok method.

QUnit.ok(true, 'This is true');//If true it passes

If you know that something must throw an exception in a specific case, than you can call the expected method that throw inside the throws method. You can specify an expected error object to match the thrown exception also.

QUnit.throws(()=>{});// Test if something has been thrown with  throw "error"...

Another way to test is to see how many assertions have been called. This is useful in case of looping and call back function. The expect method must be used before any assertion inside the test method.

QUnit.expect(3); // Expect to have 3 asserts, good for call back method testing

QUnit is a small framework that allow you to test you JavaScript. It is compatible with TypeScript and you can find the definition file at GitHub.

How To Debug With Visual Studio And TypeScript

If you have Visual Studio 2013 Service Pack 3 it is easy to debug TypeScript within Visual Studio, directly from TypeScript source code. First of all, go in the Solution Explorer and right click the solution you are executing. Second, go in the project property under the TypeScript Build tab. Check in the Debugging Panel “Generate source maps”.

GenerateSourceMaps

This is it. You just need to set a breakpoint and you are in business.

An Introduction Of How To Load Asynchronously JavaScript Files

JavaScript files are loaded synchronously from the top to the bottom of the script tag in your html page. This has the advantage to handle correctly references. You can use from a file that is loaded later functions from a file that was loaded earlier. For example, if you set the script tag to load JQuery as the first script to load, every subsequent JavaScript files will be able to use JQuery. However, the problem is that you are losing performance because every files are in a queue to be downloaded. Several options exist like bundling all JavaScript into a single file or to activate in your web server SPDY protocol. But, it still does not fix another problem which is to divide JavaScript file to work by module. This way, you could have reusable modules that could be loaded depending of the need instead of having a huge bundle. This technic is called AMD. AMD for Asynchronous Module Definition. It is a mechanism for defining modules, their dependencies and can load asynchronously all of them.

Open source projects exist that do AMD for JavaScript. One of them is amdjs and a second one is RequireJS. Both work with the same principle of defining module id which associate one or multiple JavaScript file to an unique identifier.

In this article, I will concentrate on RequireJS which is in my opinion very well documented and easier to understand. To get started, you need to remove from your project all your JavaScript references. You only need to have the RequireJS and to define its bootstrapper function. In the example below, you have your bootstrapper method called main.js that must be defined in the data-main attribute of a script tag that define the source to require.js.

<script data-main="scripts/main.js" src="scripts/require.js"></script>

The example above could have been written without the .js for the main attribute. This is because RequireJS knows that we are handling JavaScript file and will handle extension byitself if the reference does not start with an http protocol (http or https) or does not start with a slash (/). Advanced configurations are possible for path like defining specific path alias for folders or to define the base path. You can find more information directly on RequireJS Api Web Page.

Once paths are define you can now decide which JavaScript file to load for the page you want. The example below is from RequireJs. It loads JQuery, a JavaScript for canvas and something that use a predefined subpath called “app” that us a module named “sub”.

requirejs(['jquery', 'canvas', 'app/sub'],
function   ($,  canvas, sub) {
    // Every module are loaded here
});

Inside your JavaScript files, you can define dependencies. This is where all the modularity kick in. This example also come from RequireJS Api Web Page. It is the code that is set at the top of the shirt.js file which depend on the cart.js and inventory.js file. The define functions takes in its first parameter an array of module that the file depends. The second parameter is a function that takes the same amount of the dependent module. This also us to have a reference to the dependent module. You can see that like the Dependency Injection pattern.

define(["./cart", "./inventory"], function(cart, inventory) {
        //return an object to define the "my/shirt" module.
        return {
            color: "blue",
            size: "large",
            addToCart: function() {
                inventory.decrement(this);
                cart.add(this);
            }
        }
    }
);

Let’s dive in a short demo. Create a simple Html file with that call the bootstrap of Require.js.

<!DOCTYPE html>
<html>
    <head>
        <script data-main="scripts/main" 
				src="scripts/require.js"></script>
    </head>
    <body>
    </body>
</html>

This imply that we set the require.js file, that you can download from the official website, to be installed into a scripts directory. In that directory we will set the main.js file and a folder that will contain another JavaScript file. This will let you demo JavaScript files in different folders.

requireExample

The main JavaScript will require the use of the other JavaScript in the other folder.

console.log("Main: Before Require");
require(["helper/util"], function(util) 
{
    console.log("Main: After Util loaded");
});
console.log("Main: After Require");

And the util will be a plain JavaScript that just show in the console the output.

console.log("Util: Util file is loaded");

The end result is what we expect, the two logs of main.js are executed before the one in util.js. The last log is the one defined in the function inside the require which is trigged only when the util.js is finally loaded.

requireOutput

So far we have seen the possibility of the modularity but not the asynchronous feature. To show this in action, let’s create some more JavaScript file and modify the main.js to load more than only a single file.

console.log("Main: Before Require");
require(["helper/util","helper/util2","helper/util3"], function(util) 
{
    console.log("Main: After all Util loaded");
});
console.log("Main: After Require");

The output is about the same but now we have three JavaScript file loaded in parallel.
requireAsync

Let’s do a comparison of these JavaScript files loaded without Require.js to see how it would have looks.
requireNoRequireOuputPerformance

It is not really different because these file are small but they are not loaded in the same time. However, we see that using Require.js has a performance penalty for small JavaScript file. The time is almost the double when using Require.js in this very small test. It worth to check it out with bigger library. It is also important to keep in mind that it is not only about performance but about modules.

Entity Framework Copy All Scalar Properties From An Existing Entity

Entity Framework gives the possibility to create a new instance with properties of an existing entity with a single line instruction. The function that verify every properties and compare them with the one in the context is inside the Entry function under the name SetValues.

Let’s set up the code to try an update on an existing entity. First, let’s create the entity in its own context. This way we insert the entity in the database and kill the context.

//Create a person
using (var context = new YourContext())
{
	var person = new Person { Name = "WorkingWithEntry", BirthDate = DateTime.Now };
	context.Set<Person>().Add(person);
	context.SaveChanges();
}

The second step is to load from the database the person into a variable that will be used in another context. This simulate the scenario of a disconnected entity. It is loaded of values but the next context will not know about it.

using (var context = new YourContext())
{
    personLoaded = context.Set<Person>().Single(sd => sd.Name == "WorkingWithEntry");
}

Finally, we do a single change or multiple changes to the disconnected entity and call the SetValues. But before calling this method, we must change at least one property. In the example below, we change the name.

personLoaded.Name = "Modified Name";
using (var context = new YourContext())
{
    context.Configuration.AutoDetectChangesEnabled = false;
    context.Configuration.ProxyCreationEnabled = false;
    var copy = new Person();
    context.Entry(copy).State = EntityState.Added;//The context must know the entity to do the copy to.
    context.Entry(copy).CurrentValues.SetValues(personLoaded); //The context must also know the entity to copy from.
    copy.Name = "This is a copy AKA clone";
    context.SaveChanges();
}

After changing the name, we create a new instance of Person and add this new instance to the context by using the Entry method and set the state to Added. We could also use the .Add method which does the same thing. The next step is to use the SetValues with the entity that contains all changes. Entity Framework will match all properties name and assign values if required. Of course, it is possible to change after calling this method properties to have something unique.

It is not required to use that method if you are modifying an existing entity. Changing the state to Modified do the job. Here is the complete code with the Modified used to an existing entity.

private static void WorkingWithEntryAndAllScalarProperties()
{
    Person personLoaded;

    //Create a person
    using (var context = new YourContext())
    {
        var person = new Person { Name = "WorkingWithEntry", BirthDate = DateTime.Now };
        context.Set<Person>().Add(person);
        context.SaveChanges();
    }

    //Load the person
    using (var context = new YourContext())
    {
        personLoaded = context.Set<Person>().Single(sd => sd.Name == "WorkingWithEntry");
    }

    personLoaded.Name = "Modified Name";

    //Save the person (modified its properties)
    using (var context = new YourContext())
    {
        context.Configuration.AutoDetectChangesEnabled = false;
        context.Configuration.ProxyCreationEnabled = false;

        context.Entry(personLoaded).State = EntityState.Modified;
        context.SaveChanges();
          
        var copy = new Person();
        context.Entry(copy).State = EntityState.Added;//The context must know the entity to do the copy to.
        context.Entry(copy).CurrentValues.SetValues(personLoaded); //The context must also know the entity to copy from.
        copy.Name = "This is a copy AKA clone";
        context.SaveChanges();
    }
}

The SQL generated by this code for the SaveChanges() after the EntityState.Modified is a huge one with all properties updated, even those that has not changed.

exec sp_executesql N'UPDATE [dbo].[People]
SET [Name] = @0, [BirthDate] = @1
WHERE ([Id] = @2)
',N'@0 nvarchar(max) ,@1 datetime2(7),@2 int',@0=N'Modified Name',@1='2014-07-31 12:00:05.9600000',@2=12

If you want to update only specific fields in the table you have to set the property to modified instead of the whole entity like the code below.

private static void UpdatingASpecificFieldOfATable()
{
    Person person;

    //Create a person
    using (var context = new YourContext())
    {
        person = new Person { Name = "Update only a single property", BirthDate = DateTime.Now };
        context.Set<Person>().Add(person);
        context.SaveChanges();
    }

    //Update a single field
    using (var context = new YourContext())
    {
        context.Configuration.AutoDetectChangesEnabled = false;
        context.Configuration.ProxyCreationEnabled = false;
        context.Entry(person).State = EntityState.Unchanged; //In the context without any modification
        person.BirthDate = new DateTime(1984, 08, 01);
        person.Name = "This will not be saved in the database";
        context.Entry(person).Property(d => d.BirthDate).IsModified = true;
        //context.Entry(person).Property(d => d.Name).IsModified = false;
        context.SaveChanges();
    }
}

It is important to see that I have commented the line that set to IsModified to False the name. We do not need to specify properties that is not modified if we have AutoDetectChangesEnabled to false. In the case that it is to true, you need to set it manually to false because Entity Framework detects a changes when setting the propreties. The goal here is to modify the Name and the BirthDate property but only allow the update of the BirthDate. Here is a screenshot of the database.
SinglePropertyChanged

We are over the subject of SetValues with the Entry and Modified property. However, it is interesting to see that you can have a lot of control about what you want to be modified or not with Entity Framework. You can see the code of this article on GitHub or download a zip file with the source code.

Entity Framework Using Foreign Key Property Instead of Property

Entity Framework allows to have two types of association. The first one require less change in your classes because it uses the normal way to have association in oriented object. This is called independent association. For example, if you have a CAR class that has an OWNER than you just need to have in your CAR class a property of OWNER type. With Entity Framework, you will need to do something when saving the entity if you do not want to have a new instance of the OWNER. This can be done by attaching or by setting the property with Entity Framework to EntityState.Unchanged. However, it is simpler if you add in your classes not only the property of the type but also an additional property with the foreign key. For example, your CAR class could have the property of OWNER but also OWNERID.

public class Car
{
    public int Id { get; set; }
    public string Type { get; set; }
    public Person Owner { get; set; }
    public int OwnerId { get; set; }
}
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }
}

Creating a new Car and associating the car to a Person (Owner) can be done without having to do any hard code. The code below adds a Person and then create a new Car with an association to the person that own the car.

private static void AddByIdInsteadOfProperty()
{
    using (var context = new YourContext())
    {
        var person = new Person { Name = "Automatically added from the property", BirthDate = DateTime.Now };
        context.Set<Person>().Add(person);
        context.SaveChanges();
        Console.WriteLine("Person id = " + person.Id);
        var car = new Car {OwnerId = person.Id, Type = "Honda"};
        context.Set<Car>().Add(car);
        context.SaveChanges();
        Console.WriteLine("Car id = " + car.Id);
    }
}

Without this property you would have to set the Owner property to a new Person with this one at the id of the existing person previously created. But, this will try to add the person and will crash because Entity Framework will try to insert an entity with an existing ID. To fix this, we need to set the property state to attached and it everything would commit without a problem. The reason that it is simpler to the property ID defined is that Entity Framework tracks only scalar property. Scalar property is a property with primitive value.

You can find the code here or download the Zip file here.