Archive

Archive for August, 2012

Distributed Systems

August 31, 2012 Leave a comment

In November, I will be heading to Miami to attend Udi Dahan’s “Advanced Distributed System Design” course.  I’m very excited to have a chance to meet and learn from someone as accomplished as Udi.  All the reviews of the course that I’ve read so far have basically echoed one thing: be prepared to have an eye opening experience.

As my company continues to invest in SOA, I feel the need to have a deeper understanding and perspective of distributed systems.  There’s no doubt that I will be overwhelmed by the amount of information presented.  I hope to come out of the course with a better understanding of how distributed systems should be designed and be able to explain the benefits to others.

Scope in JavaScript

August 6, 2012 Leave a comment

One of the things I commonly see confuse C# developers when they start working with JavaScript is how different scoping is compared C#. The code below will alert “2” twice. The equivalent C# code would cause a compile time error because “num” already exists in the current scope.

var num = 1;

if (num == 1) {
	var num = 2;
	alert(num);
}
	
alert(num);

Because JavaScript has function-level scope, blocks do not create a new scope. When we do require block-level scope, we may use an anonymous function to create a new scope.

var num = 1;

if (true) {
	(function() {            
		var num = 2;
		alert(num);
	})();
}

alert(num);

The code below will alert “2” once. The reason is because the variable declaration for “num” is actually moved to the top of the function scope.

var num = 1;

(function() { 
	if (num) { 
		alert(num);
	}

	var num = 2;
	alert(num);
})();

This code is functionally equivalent to:

var num = 1;

(function() { 
	var num;

	// "num" is undefined at this point.
	if (num) { 
		alert(num);
	}

	num = 2;
	alert(num);
})();

Variable declarations are moved to the top, even if they are unreachable or dead code. This code will alert “2” then “1”:

var num = 1;

(function() {
	if (!num) {
		num = 2;
	}
	
	alert(num);
	
	return;
	var num = 99;
})();

alert(num);

If we removed the variable declaration in the inner scope, this code will alert “1” twice:

var num = 1;

(function() {
	if (!num) {
		num = 2;
	}
	
	alert(num);
	
	return;
	//var num = 99;
})();

alert(num);