Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Monday, October 17, 2016

process.nextTick() vs setImmediate() vs setTimeout() in node


Process management in Event loop


setTimeout() :

Definition: setTimeout is used to schedule a function  after some time in future ,i.e the function will run after given time.

Example
console.log("first") ;
setTimeout(function(){
console.log("second");
},2000); 
console.log('third');

Output: 

first
third


second

To understand setImmediate we must first understand few terms: 

Event Queue: This is a queue where all the callbacks/events gets stored while event loop is busy.

Tick: Each time the event loop takes callbacks/events from the event Queue for processing this is called tick.   


setImmediate() :-

Defination: setImmediate is used to schedule a function at end of the event queue (after all callbacks/events present at that time in event queue).

This is used for heavy CPU processing operations. These heavy operations can be scheduled at last using above functions so that other callbacks/events does not wait in the queue for completion of heavy tasks.

Example
console.log("first");
setImmediate(function(){
console.log("second");
});
console.log("third");

Output: 

first
third
second

Note: SetImmediate takes precedence over setTimeout & setImterval but not other callbacks.

process.nextTick(): - 

Defination: process.nextTick is used to schedule a function at front of event queue(before all callbacks/ event s waiting in the event queue).

This method is used when you want  to run some function in a fresh call stack like highly recursive functions.Since process.nextTick() puts the function on top of the event queue.So after completion of the current executing code , the event loop starts processing next function present in event queue which is you process.nextTick function in an fresh call stack.

Example
console.log("first");
process.nextTick(function(){
console.log("second");
});
console.log("third");

Output: 
first
third


second

Difference between setImmediate and process.nextTick:

process.nextTick adds in front of all callbacks and event loop while setImmediate adds at the end.

Example:
for(var i=0;i<3;i++){
fs.readFile("abc.mkv",function(err, data){
if(err){
console.log(err);
}else{
setImmediate(function(){
console.log("completed set immediate");
});
console.log("completed calback");
}
});
}
console.log('event emitted');

Output:

In the above example, I am reading a file in a loop for 3 times.After the file is read i.e  the callback returns , i have used setImmediate with a function that needs to be added in the event queue.This is simple function that prints some message in the console.
As you can see here that, "completed set immediate" is printed at last . This shows that   these were added at end of callback of read file.

Running the same function process.nextTick();
for(var i=0;i<3;i++){
fs.readFile("abc.mkv",function(err, data){
if(err){
console.log(err);
}else{
process.nextTick(function(){
console.log("completed set immediate");
});
console.log("completed calback");
}
});
}

Output:

As you can see in the output, completed set immediate is printed as soon the current callback execution is over.that means the process.nextTick adds in top of the event queue. 

Friday, October 14, 2016

Understanding Closures and its uses In JavaScript


Understanding Closures in Details and  using it practically In JavaScript 


Basic understanding:

A closure is an inner function that has access to outer function variables.

Example:

function foo(){
var name = "furious";
function zoo(){
return "your name is "+ name;
}
return zoo();
}
foo();

As you can see the inner zoo function can access outer foo function variable name.

Practical Implementation/Use:

  • Creating a variable that retains its value in multiple executions like static variables in Java.
    Example: Creating a counter that is incremented on each page view.
    Lets take the below function and check its output.
var counter = function(){
var count = 0;
++count;
console.log(count);
}
}
counter();
counter();
counter();

Output:
1
1
1


As you can see each time the output is 1 because the counter value is always initialized by 0 when the program is executed multiple times.

Now Lets take below example:
var counter = function(){
var count = 0;
return function(){
++count;
console.log(count);
}
}

var increment_pageviews = counter();

increment_pageviews();
increment_pageviews();
increment_pageviews();

Output : 

1
2
3

Run increment_pageviews() multiple times and you can see that the value is  incremented each time.So in above example the value of count is retained.


  • Creating a private variable that cannot be accessed outside the function and its value can only be changed by internal functions like private data members in Java.

    Example: Expanding above example of counters :
  • var counter = function(){
    var count =0;
    return {
    increment : function(){
    console.log (++count);
    return count;
    } ,
    decrement: function(){
    console.log(--count);
    return count ;
    },
    reset : function(){
    count =0;
    console.log(count);
    return count;
    }
    }
    }

    var pageviews = counter();
    pageviews.increment();
    pageviews.increment();
    pageviews.increment();
    pageviews.decrement();
    pageviews.reset();

    output :

    1
    2
    3
    2
    0

    As we can see here that count is a private variable  and can only be manipulated by 3 exposed public function increment(), decrement() & reset() only.

    Deeper Dive into Closures

    Let us take the below example: 
    function add(int x){
    var count = 0 ;
    return function(){
    count += x;
    console.log(count);
    return count;
    }
    }

    var sum = add(3);
    sum();
    sum();
    sum();

    Output:
    3
    6
    9

    Now If the concept of closures was not present , then the above function would have given below output :
    3
    3
    3

    Lets see how closures helps to retains the value of the count variable.
    Now, As we know each function in the javascript has his own heap space where it keeps its variables and reference of the inner functions.
    Also when the function execution is completed & there is no reference for that function i.e there is no reference available for that function the garbage collector clears the heap and remoes all the items in that memory.

    In case of above example
    the first heap area is created for the file, which stores the empty variable sum and reference to function add().

    When add(3) is executed , Another heap area is created  which stores the variable count & reference for inner anonymous add function.

    The reference of this inner anonymous function is also stored in the sum variable of the parent heap.
    Now after the execution of the add function is completed , ideally the count variable must have destroyed. But since there is one more variable sum in the main/parent heap which is having the reference of the inner anonymous function , the heap of add function is not cleaned by garbage collector.So whenever the sum function is called the value stored in the parent heap is incremented & returned. This is the reason why the value of the count is retained in every call .

    Please refer below video for more detailed study of this feature called closure:







    Thursday, October 6, 2016

    Alphanumeric Sorting in JavaScript using sort function


    Sorting using sort() function in JavaScript


    Function sort() is basically used for sorting an array in JavaScript.

    Let us take few sample codes and see how this function behaves with arrays of different types of elements such as numbers , strings , alphanumeric etc.

    Example 1: 
    var ar = [11,23,7,189,9,550];
    var result = ar.sort();
    console.log(result);

    Output: [ 11, 189, 23, 550, 7, 9 ]
    • Conclusion : The above example sorts the array of Numbers is lexical / dictionary order.

    Example 2: 
    var ar = [11,23,7,189,9,550];
    var result = ar.sort(numberic_sort);
    console.log(result);

    //This function cannot be used for string comaprision
    function numberic_sort(a,b){
    return a-b;
    };

    Output : [ 7, 9, 11, 23, 189, 550 ]
    • Conclusion : The above customized function sorts the array of numbers in ascending order.

    Example 3:
    var ar = ["as","asddd","trhs","oocww","wfewf","kcnw","qmdkvcn","acwwev"];
    var result = ar.sort();
    console.log(result);

    Output: 
    'acwwev',
    'as',
    'asddd',
    'kcnw',
    'oocww',
    'qmdkvcn',
    'trhs',
    'wfewf' ]
    • Conclusion : The above example sorts the array of Strings is lexical / dictionary order.

    Example 4:
    var ar = ["csnc33","cddsc1","cwew91","fdwef62","vc2211","2831nb1","7dsv7sv","ncnd777","22nbebe","ewfwef873bttbbbbbgc","fdwef69","fdwef61","123","njahy","125","0.342"];
    var result = ar.sort();
    console.log(result);

    Output : [
    '0.342',
    '123',
    '125',
    '22nbebe',
    '2831nb1',
    '7dsv7sv',
    'cddsc1',
    'csnc33',
    'cwew91',
    'ewfwef873bttbbbbbgc',
    'fdwef61',
    'fdwef62',
    'fdwef69',
    'ncnd777',
    'njahy',
    'vc2211' ]
    • Conclusion : The above example also sorts the array of Strings is lexical / dictionary order.

    Example 5:
    var ar = ["A","a","1",1,"cascsac","cccead","treave","mvwen","VV344FFVveve323","v8e8v98vvd","3234223","3332csdvv3","323","3451","68564","11243","562",45,2352,255,0.432,64.223,"5545.454"];
    var result = ar.sort();
    console.log(result);

    Output : 
    0.432,
    1,
    '1',
    '11243',
    2352,
    255,
    '323',
    '3234223',
    '3332csdvv3',
    '3451',
    45,
    '5545.454',
    '562',
    64.223,
    '68564',
    'A',
    'VV344FFVveve323',
    'a',
    'cascsac',
    'cccead',
    'mvwen',
    'treave',
    'v8e8v98vvd' ]

    Conclusion: 
    • By default ,All the values are compared as strings in sort function , hence sorting is in lexical/dictionary order.
    • Sorting Order :  numbers -> capital Alphabets -> small alphabets
    • Example  :  [1, "1", "1a", "A" ,"a", "b1"]  (Ascending order) 

    Let us take Some more example , but now with Comparison Operators such as  > , <  , == etc


    • 1 < 2 true
    • "1" < "2"  true
    • "1" == 1  true
    • "1" < "a"   true
    • "1" < "sacacasc"  true
    • "0.3" < "svs"  true
    • "sscsd" < "sscsd8776"  true

    As you can see from above examples that comparison operator also woks similar as sort function.
    It also compares values as strings and hence gives results according to lexical order.