Monday, January 13, 2014

JavaScript Best Practices : Variable scoping and hoisting

You may also like to see:


Hoist means in dictionary is "to raise(going up) by means of ropes or pulleys".


In this article we will see hoisting effect of variable in JavaScript. What would be its effect and how to escape these situations?


Lets start with a example code:


var x = 1;
function myFunction() {    
   if (!x) {
     var x = 10;
   }
   alert(x);
}
myFunction();

If you know about JavaScript closures, the function here myFunction have the access to variable x defined outside of the function and in JavaScript 1 = true so condition if(!true) will fail here and alert of value 1 will be prompted at end.

If you are thinking as above the you might be surprised knowing that it is not true.

See here jsFiddle Demo

if you run this code it will give you alert of 10.

Why it is behaving like this?

It is because of Hoisting in JavaScript. Hoisting move the declaration part to the top of scope automatically but not the initialization part.



so above given example code actually treated as:

var x; //declaring hoisted part
x = 1; //initialization not hoisting
function myFunction() {    
  var x;  // hoisted and overwrite outerscope x with undefined  
  if (!x) {
    x = 10;  //not hoisted
  }
  alert(x);
}
myFunction();

That is the reason when myFunction was called it actually overwrite(mask) the parent scope variable and at condition statement it value was undefined due to NOT operator it gets true now value initialized with value 10.

Hoisting also occurs with function, it hoist completely with its body part that is the reason in JavaScript calling function before its declaration.

myFunction();// it will call function without error

function myFunction() {    
   console.log('function get called');
}

above code throws no error (jsFiddle Demo) as it is interpreted as:

function myFunction() {    
   console.log('function get called');
}

myFunction();


How to use this knowledge?


As now you know how confusing variable hoisting can be.In large block of code it is really difficult to understand the scope and hoisting effect which may cause unexpected results. So to avoid this situation always use single var pattern according which define all variables with a single var at the top of scope. Benefits of this technique is that you can find all variable at single place, helps in variable name conflicts and hoisting effect.


You may also like to see:

Saturday, January 11, 2014

JavaScript Best Practices : loop optimization

You may also like to see:

As JavaScript is a client sided programming language, JavaScript should not do any complex or really difficult algorithms which take a lot of time computation.As it may cause to hang the browser or affect your site performance.


There are many things to optimize in a code, In this article I will try to discuss some techniques using we can optimize loops in JavaScript.



A simple loop in JavaScript is:



var fruits = ["apple","banana","orange","mango"];
for(var i = 0; i < fruits.length; i++) {
  // do something with fruits[i]
}

See Performance Demo here

This is simplest loop, we don't need to optimize it but if there are a huge number of items in the array to iterate on or there is complex logic in loop to implement, then we might need to make it faster. Following are some optimizations we can implement on this loop.  

Cache the condition to break

This loop will break when variable i is equals to length of the array, each time array checks this condition it will get the length from object, which is just a overhead. We can get the length of the array and assign it variable and use that variable so we don't need to calculate the length each time. This small trick is really beneficial when iterating over huge items.

var fruits = ["apple","banana","orange","mango"];  
for (var i = 0, max = fruits.length;i < max; i++) {    
   // do something with fruits[i] 
} 

See Performance Demo here

Now this will initialize once then it will use the max variable in each iteration.

(Note: Here initialization of i and max is separated with comma not semi-colan var i = 0, max = fruits.length;  

Single var Pattern

According to single var pattern:
Initializing all variable with single var at common place helps to control the scope of variables and avoiding collisions of variable names, unused variables or preventing logical issues due to uninitialized items. If there are 1000 variables and you initialized it with single var keyword, will save your more than 3000 characters which make your code lesser in size and make it even readable after minifying with some tool.

Using a single var for initialization of all the variable include in iteration can further optimize the performance, with a minor drawback of making copy-paste harder for a loop when refactoring a code.

var i, max, fruits = ["apple","banana","orange","mango"]; 
for (i = 0, max = fruits.length;i < max; i++) {
   // do something with fruits[i]
}

Making simplest increment  

i++ is a bit tricky operator what it actually do:
  • make a temporary copy of variable i
  • increment variable i
  • return the temporary copy for current use
so replacing this with i += 1 or i=i+1 will effect the loop positively.

var i, max, fruits = ["apple","banana","orange","mango"]; 
for (i = 0, max = fruits.length;i < max; i+=1) {
   // do something with fruits[i]
}

See Performance Demo here

Reverse loop

If we iterating over a loop for all the elements in a collection reverse loop starting from a length of collection to zero is faster than above given techniques, it completely depends on the situation whether to use this technique or not. As zero in JavaScript is equal to false so it will automatically break the loop on zero. In this technique condition testing and decrement is occurring in one step which making performance faster.

var i, fruits = ["apple","banana","orange","mango"]; 
for (i = fruits.length; i-=1;) {
   // do something with fruits[i]
}

See Performance Demo here

Making cleaner while-loop

If reverse loop iteration is possible then making it as while loop is more cleaner, it would not make code faster but will surely make it cleaner, readable, easy to understand.

var fruits = ["apple","banana","orange","mango"],i = fruits.length;
while(i-=1) {  //for readability use i--
   // do something with fruits[i]
}


See decrement operator performance difference here.

Summary

It is not necessary that you always get benefits from using these best practices as in small collection all above techniques might produce performance but when you are implementing complex algorithms with a number of collections then you will get the benefits of good code. So making it practice to use best practices always, will make your code and performance better even when you not realize it.


You may also like to see:

Saturday, January 4, 2014

JavaScript Triple Equals Operator vs Double Equals Operator ( === vs == )

You may also like to see:








Comparing two values in any language is the most used operations. In many cases you may need to compare different variables values, that is the reason in many JavaScript code you will find following lines:


if (age == years) {  
    // do something here  
}  

or JavaScript which follows best practices, you will find:

if (age === years) {  
    // do something here  
}  

Operation in the first example is also called "lenient" or "normal" equality while the latter one is also called “strict” or “identical” equality.

Why different operator?

When a comparison is made using a double-equals operator, it will check the values of a variable and convert them to a common type and returns true if both are equals. So comparing number with a string having the same value will return true.

JavaScript supports different data types which includes string, number, booleans, array, object, function, null and undefined. When comparing different types with double equals operator an implicit conversion is occurring and then the comparison is made. This conversion is made for boolean to a number when comparing numbers with boolean, or number to string when comparing string with numbers.

This conversion not only an overhead but also give unexpected(wrong) output in many cases.

Here are some examples:

console.log(23 == "23"); // true  
console.log(1 == true); // true  

Some programmers find it useful that auto-conversion is making it easy to compare, but it is not always the case. It may cause serious issues.

For example:

console.log(' \r\t\n' == 0); // true  
console.log(0 == ' '); // true  

Here in these cases space is converted to false or zero which causing the result true in both above cases. Which may cause your comparison to going in wrong directions.

That is the reason most of the JavaScript expert programmers use and recommend triple-equals operator instead of the double-equal operator.

As Douglas Crockford's stated in his book JavaScript: The Good Parts:

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:


'' == '0'   // returns false
    0 == ''             // returns true
    0 == '0'            // returns true

    false == 'false'    // returns false
    false == '0'        // returns true

    false == undefined  // returns false
    false == null       // returns false
    null == undefined   // returns true

    ' \t\r\n ' == 0     // returns true

In contrast to double equals operator, another operator with three equals not made the implicit conversion so it not only compare values but also the type of variable that's why it is also called strict comparison.

Due to not implicit conversion, it is not only better in performance but guarantees the correct results always.

Here are examples:

console.log(23 === "23");  // returns false  
console.log(1 === true);  // returns false  
console.log(' \t\r\n' === 0); // returns false  
console.log(0 === ' '); // returns false  

Not-Equals to Operator?

Same situation or output is return when not-equals to comparison is made between two variables using != or !== operators

Here are examples:

console.log(23 != "23"); // false  
console.log(1 != true); // false  
console.log(' \t\r\n' != 0); // false  
console.log(0 != ' '); // false  

As expected result should be true from above comparison but due to implicit conversion, all comparison return true.

To make it work correctly use !== operator:

console.log(23 !== "23"); // true  
console.log(1 !== true); // true  
console.log(' \t\r\n' !== 0); // true  
console.log(0 !== ' '); // true  

Comparison in Reference Types

When comparing non-primitive data types (reference types) both operators behave consistent (except in some cases discussed below)

Here are some example:
var arrayOne = [1,2,3];
var arrayTwo = [1,2,3];

var objectOne = { x: 1, y: 2 };
var objectTwo = { x: 1, y: 2 };

arrayOne == arrayTwo    // false
arrayOne === arrayTwo   // false

objectOne == objectTwo   // false
objectOne === objectTwo  // false

A special case is the one when you comparing primitive type with an object that returns the same primitive type due to valueOf or toString methods. The special cases include comparing primitive string compare to new String() object or primitive number compare with a new Number() object or same for boolean.

Here are examples:

new String("abc") == "abc"   // returns true
new String("abc") === "abc" // returns false

Here triple equals operator returned false as it matches types of both sides which are string and object. while double equals operator returned true it matches value after conversion.


Performance Comparison

When comparing two variables of same data type, both operator takes almost equal time. But if the type is not same triple equals operator will be faster because it would not try to convert the types of variable causing it sooner to exit than double equals operator.

Hera another point to notice that triple equals operator has one extra character, so using it might increase the JavaScript file size which may take the time to load but this is negligible.

Performance Test of both operator with same and different data types.

So, I may conclude it by recommending always to use triple equals operators, which may sometime make you to do explicit conversion but it prevent from unexpected and wrong output. It is one best practice recommend by many JavaScript experts. Like Douglas Crockford's says:

The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==.

You may also like to see:

Friday, January 3, 2014

Data Types In JavaScript

You may also like to see:





JavaScript is a dynamic typed (or termed as Loosely Typed) scripting language which means that same variable can be assigned data of different types.





Here is example (JsFiddle):


var dynamicVariable;               // Now dynamicVariable is undefined
dynamicVariable = 10;           // Now dynamicVariable is a Number
dynamicVariable = "Hello JavaScript";// Now dynamicVariable is a String
dynamicVariable = true         //Now dynamicVariable is a boolean

Variables in JavaScript is initialized with var keyword instead of data type itself like C, C++, C# or Java.

There are six Data Types in JavaScript, three of them are Primitive or also known as Primary data type while everything else in JavaScript is Object or Reference Typed also known as Composite data types.

Primitive Data Types:

The primitive data types are (JsFiddle):
  • String
  • Number
  • Boolean
Reference Data Types

Other than above three primitive data types everything in JavaScript is object like function, Regexp etc. The reference data types are (JsFiddle):
  • Object
  • Array
  • Function

In JavaScript specifications typeof Array and null is object, so to confirm whether object is Array or null you can use

console.log(Object.prototype.toString.call(new Array("test","items"))); //will print [object Array]
console.log(Object.prototype.toString.call(null)); //will print [object Null]

Special Data Types:


There are two others special data types, which includes (JsFiddle):
  • null
  • undefined

String Data Type

String data type is use to represent text in JavaScript. A string is value with zero or more characters which may include letters, punctuation marks and digits. There is no separate data type for character (char) in JavaScript. You may use single or double quote for assigning value to string.

These are some examples of valid string data types in JavaScript:

var str1 = "Hi, How are you?";
var str2 = "He said: 'Hi'";
var str3 = 'He said:"Hi" ';
var str4 = "25";
var str5 = "";
var str6 = 'C';

In JavaScript you may get the data type of any variable using typeof

alert(typeof str1);

using type of on above all variables will return you string. Here is demo (JsFiddle).

Number Data Type

For any numeric values float, decimal or integer JavaScript has only one data type that is Number.

Here are some examples (JsFiddle):

var num1 = 23;   //integer value
var num2 = 42.25; //float value
var num3 = 22e5; //exponential 2200000
var num4 = 13e-5 //0.00013


Additional special value for numeric types are :

  1. NaN (not a number) to represent inappropriate data, as a result of mathematical operation
  2. Positive Infinity represents too large positive number
  3. Negative Infinity represents too large negative number
  4. Positive and Negative 0 represent positive and negative zero(JavaScript differentiate zero as positive or negative).

Boolean Data Type

Boolean data type can only have two values, literals true and false. Comparison of two variables will outcome a Boolean value. Boolean are used for condition testing.

Here is example (JsFiddle):
var num1=54; 
var result = (num1 === 2000); //will return false
var result1 = (num1 === 54); //will return true


Primitive variables as Objects

In JavaScript all variable can be of object type, for each primitive their is a Object type. You can initialize object type by using new keyword with String, Number or Boolean. It will initialize object of that type.
var str = new String; //default value is empty string ""
var num = new Number; //default value is 0
var bool = new Boolean; //default value is false

Object Data Type

Object data type is a custom data type, it can be assumed a class of object oriented language. It may contains many properties or function. Object is defined in curly braces, in these braces properties and function are defined as key-value pair.

Here is example (JsFiddle):

var person = {
    Id: 1,
    FirstName: "firstname",
    LastName: "lastname",    
    Walk: function () {
        alert("walk using two legs");
    }
};

Properties and functions can be access by property or function name with variable i.e, person.FirstName; or person.Walk().


Array Data Type

Array is collection containing zero or more items. Array items can be access by using indexing on variable. In JavaScript specifications typeof Array is object, which cause confusion. Array can be initialize in different ways.

Here are examples (JsFiddle):

var dataTypes=new Array();
dataTypes[0]="String";
dataTypes[1]="Number";
dataTypes[2]="Boolean";

//condensed array:
dataTypes=new Array("String","Number","Boolean");

//literal array:
dataTypes=["string","number","boolean"]; 


Function Data Type

In JavaScript variable may also be a function, which can be trigger using round bracket. These type of variable can be initialize by assigning function to a variable.

Here is example (JsFiddle):

var myFunc = function(){
  alert("function is triggered");
}; 

myFunc();

Null Data Type

The value for null data type can only be null. keyword null is use to assign null to any variable. It can be use to emptied content of any variable without deleting the variable. A variable with null data type contains no valid other data types.
Like Array in JavaScript typeof operator with null returns the object which is confusing behavior.

Here is example (JsFiddle):

var type = null;
var obj = null;

Undefined Data Type

The undefined value is default for a variable which is declared but never assigned a value.

Here is example (JsFiddle):

var myVar;
if((typeof var) === "undefined"){
  alert("variable is undefined");

In JavaScript best practice is to use triple-equals-operator for comparison. Detailed article here.

You may also like to see:

Life insurance policy, bank loans, software, microsoft, facebook,mortgage,policy,