JavaScript Closures

A JavaScript Closure is formed by returning a function object that was created within an execution context of a function call from that function call and assigning a reference to that inner function to a property of another object. Or by directly assigning a reference to such a function object to, for example, a global variable, a property of a globally accessible object or an object passed by reference as an argument to the outer function call.

In the example below you will notice that the globalVar has access to the exampleConcatReturn. However, it does not have access to the finishStringArg as that is seen as basically a private variable that cannot be accessed outside that function.

function exampleClosure(stringArg1, stringArg2) {
    var finishStringArg = "!";
    function exampleConcatReturn(innerArg) {
        return (stringArg1 + stringArg2 + innerArg + finishStringArg);
    }

    return exampleConcatReturn;
}

var globalVar = exampleClosure("Adam ", "Drummond "); /*stringArg1 = "Adam" and stringArg2 = Drummond*/

//Call to the function
alert(globalVar("Was Here")); /* innerArg = "Is Coding" */

/* would return Adam Drummond Was Here!*/

Another example is as follows.  This was based from Mozilla’s developers area.  I think it really does a great job in showing how the privateCounter is only used from within.  Also, you will take notice that you can create numerous functions off of the main makeCounter function and they will stay separate of each other.

var makeCounter = function () {
    var privateCounter = 0;
    function changeBy(val) {
        privateCounter += val;
    }
    return {
        increment: function () {
            changeBy(1);
        },
        decrement: function () {
            changeBy(-1);
        },
        value: function () {
            return privateCounter;
        }
    };
};

var Counter1 = makeCounter();
var Counter2 = makeCounter();

alert(Counter1.value()); /* Alerts 0 */

Counter1.increment();
Counter1.increment();

alert(Counter1.value()); /* Alerts 2 */

Counter1.decrement();

alert(Counter1.value()); /* Alerts 1 */

alert(Counter2.value()); /* Alerts 0: Notice that it doesn’t get affected by Counter1 */

As seen in this example, you have Counter1 and Counter2.  Take a look at the incrementing and decrementing of Counter1 and at the end, Counter2 is still in the same state as when it was created.


When to use Break and Continue

This is a fairly simple yet useful difference to know between break and continue when using loops or switch statements. The break statement terminates the closest enclosing loop or switch statement in which it appears. Control is passed to the statement that follows the terminated statement, if any.  The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears.   I find this wording from msdn to be slightly confusing so let’s turn to some examples.

Take this loop for instance:

for (int i = 0; i < 100; i++)
{
    if (i == 0)
    {
        break;
    }

    TestMethod(i);
}

The use of break in the above example causes the loop to exit on the first iteration of the loop. This means that our TestMethod(i) will never be executed.  This works well if you are looking through a list for a particular value, once found, there is no need to iterate through everything else.

Now let’s take a look at the continue statement:

for (int i = 0; i < 10; i++)
{
    if (i == 0)
    {
        continue;
    }

    TestMethod(i);
}

The use of the continue statement above causes the loop to skip calling the TestMethod(i) when i  == 0.  However, the iterations will continue after that and TestMethod(i) will be executed when i  == 1 all the way to i == 99.  This comes in handy if there are certain values in a list that you are not wanting to execute on; you can skip over them and continue on with executing on the rest of the values in the list.

Some closing thoughts, in whether this is best practice or not it’s debating frequently.  The main argument that arises is code readability.  If you are having a hard time reading the code this will raise the chances of you exiting before you are wanting to and can cause bugs that you do not realize.  So as always, make sure you pay attention to what you are doing and what your intent is to ensure that your program is going to perform properly.


Difference Between Ref and Out

The difference between ref and out may not be complicated but easy to mix up. This is really a post mainly for my quick reference and knowledge, but hey, it might pose a quick use for someone else too.

Ref is a keyword that causes an argument to be passed by reference, not by value.  This has an effect of when there is any change to the parameter in the method is reflected in the underlying argument variable in the calling method.   When using the ref keyword, you must use it in the method definition and in the calling method.

class ExampleForRef
{
    static void Main()
    {
        int val = 23;
        RefMethod (ref val);
        Console.WriteLine(val);

        // i = 46
    }

    static void RefMethod(ref int i)
    {
        i = i + 23;
    }
}

A ref parameter must also be initialized before it is passed.  This is a difference between ref and out because when using the out keyword, the variable does not have to be initialized before it is passed.[more]

Out is a keyword that causes arguments to be passed by reference.  This is very similar to what we just discussed above, but when using out, the variable must be initialized before it gets passed. In order to use the out parameter, the method definition and the calling method both must explicitly use the out keyword.

class ExampleForOut
{
    static void Main()
    {
        int value;
        Method(out value);

        // value is now 44
    }

    static void Method(out int i)
    {
        i = 44;
    }
}

A few notes to keep in mind. The called method is required to assign a value before the method can return.  In terms with compiling issues with overloading that may arise, the methods cannot be overloaded if the only difference is the ref and the out. This is taken from msdn:

class CS0663_Example
{
    // Compiler error CS0663: "Cannot define overloaded
    // methods that differ only on ref and out".
    public void SampleMethod(out int i) { }
    public void SampleMethod(ref int i) { }
}

However, if the ref or out parameter is only used in one method than it can be accomplish like this:

class RefOverloadExample
{
    public void SampleMethod(int i) { }
    public void SampleMethod(ref int i) { }
}

class OutOverloadExample
{
    public void SampleMethod(int i) { }
    public void SampleMethod(out int i) { i = 5; }
}

Some ending notes from my research:
-There is no boxing when a value type is passed by reference.
-Properties cannot be passed by ref or out, properties are really methods.


To Var or Not To Var

This is obviously a highly debated topic that doesn’t have a clear right or wrong answer to it.  The use of the keyword var allows you to implicitly define a type.  An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type.

For example:

var item = “table”;  //implicitely typed
string item = “table”; // explicitly typed

Some reasons that I have come across that people favor var for are that it reduces the amount of code and the time that it takes to code it. It makes sense; you use var, type your variable name and move on.  However, there are some drawbacks that can arise.  Say that you do not use a very descriptive variable naming.

var myCar = new Car(); //Clear
var i = myCar.GetSomething(); //Not Clear what i would be

So if I am a developer coming back to the code or it is within code I did not write, I am going to have to hover over it to see what exactly is returned. Time is ended up being saved in the coding aspect of it, but when bugs/enhancement/etc come up and the code goes through another read through time is lost deciphering types and variables due to poor naming conventions and var being used so loosely.

Linq does require var to be use when using on anonymous type.

var employeeQuery = from employee in company
                    where employee.Location == "USA"
                    select new { employee.Name, employee.Phone };

Since we are using an anonymous type, var is used.

However, say we have a type. Notice how it is a bit longer, but now I know exactly what my end result is and there is no question as to what the outcome is.

IEnumerable<Employee> employeeQuery = from employee in company
                                      where employee.Location == "USA"
                                      select employee;

It really seems to come down to is having a group standard from within your team.  Personally, I use explicit typing so that there is no question and I know exactly what type is going to be chosen at compile time.  As well, future developers will know exactly what my intent was and not have to try and guess what I was aiming for or simply being lazy.

Thoughts? What are your coding standards?


StackOverflow Profile