Variable Scope Chain in JavaScript

Before you start reading this post I recommend you to read Variable Scoping and Hoisting in JavaScript . In this post we will take a look on Scope Chain in JavaScript.

Let us consider you have declare a variable globally as below,


var var1 = "I am Global";
 var2 = "I am also global";
 this.var3= "I am also global"

In above code variables are declared globally, in other words they are not declared inside any function. There are few important points about above variable declaration,

  • Whenever you declare a variable globally, you create property of global object. So we can say var1 is property of global object.
  • Since var1 is property of global object so it is not configurable. It cannot be deleted.
  • We are creating var2 without var keyword. It is possible to declare variable without var, if we are not in strict mode.
  • In JavaScript global object can be accessed via this keyword.

Any property of global object cannot be deleted. Others can be deleted. So let us consider below code,


var var1 = "I am Global";
 var2 = "I am also global";
 this.var3= "I am also global"
 console.log(delete var1);
 console.log(delete var2);
 console.log(delete var3);

As we disused earlier var1 is not configurable so it cannot be deleted whereas other variables can be deleted. You will get output as below,

image

Above concept was very important in understating Scope Chain in JavaScript. JavaScript variables has scope

  • In function they are defined
  • If defined globally then throughout the program.

Let us consider following code snippet,

var var1 = "hello";
 function funct1() {

var var2 = "hello function";

 function funct2() {

var var3 = "hello nested function";
 }
 }

In JavaScript each function or chunk of code (for example if-else) has a scope chain. Scope chain can be seen as list of objects or objects connected to each other as chain and any variable defined inside that has a scope in that particular chain.

image

Objects in above code snippet can be viewed as following. Consider variable var2. JavaScript will first search var2 as property of funct2. If it does not find that then it will search var2 as property of object of funct2 and so on it keep searching unless it reach global object. If it does not find variable in global object then JavaScript throw ReferenceError.

Concept of Scope Chain is very useful in understating closure in JavaScript. I hope you find this post useful. Thanks for reading.

Get it right: null and undefined in JavaScript

Well, whenever I talk to developers, I find them in confusion about null and undefined in JavaScript. In this post I try to simplify understanding of null and undefined in JavaScript.

To start with null is language keyword and undefined in value of a variable. Both evaluates to value that indicates absence of a value.

To understand it better we can say null indicates an object with no value. Let us consider following code on null,


var result = typeof (null);
 console.log(result);

This will return you output as object. So to conclude we can say null is an object which contains no value or represents no object.

On the other hand undefined represents absence of value in a variable. Undefined is value of a variable. You get undefined value for a variable in following scenario

  • When variable is declared but not initialized
  • When function does not return a value
  • As value of function parameter which is not being passed
  • On accessing Array with index which does not exist
  • When accessing object property which does not exist

Let us consider following code on undefined,


var result = typeof (undefined);
 console.log(result);

This will return you output as undefined.

Other important difference is you cannot assigned undefined to a variable, whereas you can assign null to a variable. Undefined is read only.

Let us consider following code. It indicates that null and undefined represents same value that is absence of value but both are not same.


if (null == undefined) {
 console.log("both indicates absense of value");
 }

if (null === undefined) {
 console.log("both are same");
 }
 else {

console.log("both are not same");
 }

In last I will conclude that both undefined and null are falsy value in JavaScript. Both does not contain any property or methods.

I hope now you have better understanding on undefined and null in JavaScript. Thanks for reading.

Single Responsibility Principle in C-Sharp: Simplified

Let us start with understanding what is SRP?

Single Responsibility Principle says every class should have single responsibility and all the responsibility should be encapsulated in the class. To explain it further assume you are creating a creating class to Calculate Salary.

Now if you have two methods in class like below. Usually we can think of these two methods in a Salary class.

  1. CalculateSalaray
  2. PrintSalary

So you can say there are two responsibilities to class. With two responsibilities Salary class can be defined as below,

 class Salary

{
 public double wageperday { get; set; }
 public int attendence { get; set; }
 public double CalculateSalaray()
 {
 return this.wageperday * this.attendence;

}

public void PrintSalaray()
 {
 Console.WriteLine(this.wageperday * this.attendence);

}

}


As of Martin SRP means, “Class should have a single reason to change”. Reason to change can be seen as a Responsibility. On seeing closely you will find above class has two reasons to change,

  1. When formula for calculate salary is changing
  2. When print logic is changing

Since Salary class has two responsibility so there are two reasons to change it. We can say Salary class is not following Single Repository Principle.

We can summarize that

image

Next we need to find that how could we divide two responsibility in two separate class. So above Salary class can be divided into two separate classes. One class to CalculateSalary and another to PrintSalary.

Below is the class CalculateSalary. This class got only one responsibility to calculate salary.

class CalculateSalary
 {
 public double wageperday { get; set; }
 public int attendence { get; set; }
 public double CalculateSalaray()
 {
 return this.wageperday * this.attendence;

}
 }

 

Another class is PrintSalary. This class also got only one responsibility to print salary.

 class PrintSalary
 {

public void PrintSalaray(double salary)
 {
 Console.WriteLine(salary);

}
 }

Let us understand what we done now is divided Salary class in two separate classes. Salary class had two responsibilities and two reasons to change. Now we have created two classes respectively for CalculateSalary and PrintSalary.

image

Now at client these two classes can be used as below,

static void Main(string[] args)
 {
 CalculateSalary clcObject = new CalculateSalary();
 clcObject.wageperday = 300;
 clcObject.attendence = 20;
 var salary = clcObject.CalculateSalaray();
 PrintSalary prntObject = new PrintSalary();
 prntObject.PrintSalaray(salary);
 Console.ReadKey(true);

}

As of now you should have idea about Single Responsibility Principle. To summarize Single Responsibility Principle says a class should have single responsibility and only one reason to change. I hope you find this post useful. Thanks for reading.

Variable Scoping and Hoisting in JavaScript

Variable Scoping in JavaScript is quite different than other programming languages like C. In this post we will learn variable scoping in JavaScript.

Simply putting, Scope of a JavaScript variable is within region of the program it is defined. So a variable defined inside function will have scope inside that function.

Consider following code snippet,

var globalvar = "Global Variable";

 function funct1() {

var gloabalvar = "Local Variable";
 console.log(gloabalvar);
 return globalvar;
 }
 console.log(globalvar);
 var result = funct1();
 console.log(result);

You will get output as following,

clip_image001

You can see that scope of variable is within the region it is defined. We are getting second output as Local Variable because scope of globalvar is overridden in funct1 function.

Essentially variable globalvar has two different scope in above code. It has been changed inside funct1 function. So when you print its value inside funct1, you get ouput as Local Variable and outside that its value is Global Variable.

Now consider second example in this. In below example we are defining variable without keyword var.


globalvar = "Global Variable";

 function funct1() {

gloabalvar = "Local Variable";
 console.log(gloabalvar);
 return globalvar;
 }

 funct1();
 console.log(gloabalvar);

In above example inside function globalvar is getting modified and it is modifying globally scope variable. When you define a variable without var keyword, its scope is global. Output of above code would be as follows,

clip_image001[6]

Function Scope

In JavaScript works on Function Scope. In Function Scope variables are visible inside function they are defined and inside any nested function of that function.

Consider following example,


function funct1() {
 var i = 10;
 if (i == 10) {

var j = 9;
 for (var m = 0 ; m < 9 ; m++) {
 console.log(m);
 }

&nbsp;

}

console.log(m);
 console.log(j);
 console.log(i);

 }

 funct1();

In above code we are variable j and m inside if and for block respectively. In language like C there scope is limited to block they are defined. However JavaScript works on Function Scope so variable j and m are visible throughout the function. We are printing them outside block in which they are defined and JavaScript is printing them. Output of above code would be as follows,

image

JavaScript Hoisting

Just we learnt that JavaScript variables are scoped throughput the function in which they are defined. In JavaScript variables are visible before they are declared and this is known as Hoisting in JavaScript. JavaScript assumed that all the variables are declared at the top of the function. In other words all the variables are hoisted at the top of the functions.

Consider following example,


var i = 9;
 function funct1() {
 console.log(i);
 var i = 99;
 console.log(i);
 }

 funct1();
 console.log(i);

As output you will find that second print statement will print undefined. Reason behind this even if I is initialize in second line of function, it is visible throughput the function. Since I is hoisted in function so you get undefined for second print. Output of above code snippet is as follows,

clip_image001[8]

In Block Scope programming language it is better to define variables as near as possible to where they are used. Whereas due to hoisting and Function Scope in JavaScript it is better to declare a variable at the top of function.

A good understanding of Function Scope, Hoisting in JavaScript is important to write better codes. I hope you find this post useful. Thanks for reading.

Invocation patterns in JavaScript

In JavaScript you can invoke a function in four different ways. In this post we will take a look on various invocation patterns. There are four ways a function can be invoked in JavaScript. Four invocation patterns in JavaScript are as follows,

  1. Function Invocation Pattern
  2. Method Invocation Pattern
  3. Constructor Invocation Pattern
  4. Indirect Invocation Pattern

image

Function Invocation Pattern

When you call a function as an expression then it is known as Function Invocation Pattern. Let us say you have a function as given below,

 function FindSquare(number) {

return number * number;
 }

You can invoke above function as below,


var result = FindSquare(9);
 console.log(result);

&nbsp;

This way or pattern of invoking a function is called Function Invocation pattern. There are few important points about function invocation pattern is as follows,

  • First each parameter gets evaluated and then being passed as argument to function
  • Function return either value or undefined to LHS variable .If called function does not have any return value then it returns undefined
Method Invocation Pattern

In JavaScript, any function which part of an object is known as Method.

image

Assume we have a JavaScript object studentObject as following. In studentObject object property findgrade is a function. So we can say findgrade is a method.


var studentObject =
{
 name: "dj",
 marks: 89,
 findgrade: function (marks) {
 if (marks > 75) {
 return "Grade A ";
 }
 else {
 return "Grade B ";
 }
 }
}

Invocation of method is known as “Method Invocation Pattern”. We can invoke method using dot operator on object. Method can be invoked as following,

 var grade = studentObject.findgrade(99);
 console.log(grade);

A Method can access its parent object using operator this. Let us go ahead and modify studentobject as following. Now you can see that we are accessing other properties of object in method using this operator

 


var studentObject =
{
 name: "dj",
 marks: 89,
 grade: null,
 findgrade: function (marks) {
 if (marks > 75) {
 this.grade = "A";
 }
 else {
 this.grade = "B";
 }
 }
}

Now we can set grade property with invocation of findgrade method.

studentObject.findgrade(99);
 var grd = studentObject.grade;
 console.log(grd)

Binding of method to object happens when we execute the method. In this way we can work with Methods and Method Invocation Pattern in JavaScript.

 

Constructor Invocation Pattern

If you invoke a function with keyword new, then it is constructor invocation pattern. For example below we are invoking constructor


var obj = new String();
 var obj2 = new Object();

Arguments to constructors will be passed in the same way of Function Invocation Pattern. There could be scenario when constructor does not require any parameter. Then in that case constructor can be called without braces.


var obj2 = new Object;

Constructor invocation creates an empty object that inherits from prototype property of constructor.

Constructor function usually does not have return. This is used to initialize new object. It always returns a new object. Even if constructor has return statement with some primitive values, return statement will be ignored and new created object will be returned.

Indirect Invocation Pattern

You can execute a JavaScript function indirectly using function’s method as well. There are three function methods are used to execute JavaScript function indirectly. They are as follows,

  1. Call() method
  2. Apply() method
  3. Bind() method

Read more about this function’s methods here

What is Bind method in JavaScript

What is call() method in JavaScript

What is apply() method in JavaScript

These are four invocation patterns in JavaScript. I hope you find this post useful. Thanks for reading.

Presented on Backend as a Service in Pune DevCon 2013

On 24th Aug 2013 I presented on Backend as a Service in Pune DevCon 2013. It was one of the premium event with more than 300 attendees and 25 speakers. I had an opportunity to present on Backend as a Service under Windows 8 track.

image

I had a very humble audience of 30 people. I talked about following topics in my session,

  1. Windows Azure Mobile Services
  2. Icenium Everlive

I gave a demo on working with Windows Azure Mobile Services Data from a Windows Store Apps. My second demo was on working with Everlive files from Windows Store Apps.

You can read blog posts on demo I did at below links,

Fetching Windows Azure Mobile Services Data in XAML based Windows Store Application

Step by Step working with Windows Azure Mobile Service Data in JavaScript based Windows Store Apps

Step by Step working with Windows Azure Mobile Service Data in XAML based Windows Store Apps

I hope this presentation was useful for the audiences.