Jun 18, 2018

JavaScript Callback

javaScript is the new software edge. It has a vivd scope in the mobile first, IoT first and AI first world. Programming paradigm has been shifted from sequential model to event based model. And javaScript tops in it. The fundamental most important part of javaScript is function express and callback.

Function expression
Unlike C or Java a function can be assigned to a variable in javaScript
function sum ( a, b ){
  return a+b;
}
is same as
var sum = function ( a, b ) {
  return a+b;
};
Function sum can be defined in any of the above ways. The second one is called function expression. The advantage of function expression is that since the function is assigned to a variable it can be passed as a parameter to another function.!!!

See the following example.
var sum = function ( a, b ) {
  return a + b;
};
var mul = function (a, b ){
  return a * b;
};

execute ( a, b, method ){
  return method (a, b);
}

console.log ( execute ( 3, 4, sum ) ); // prints 7
console.log ( execute ( 3, 4, mul ) ); // prints 12
In the above sample a method sum or mul is passed to another method execute. It may be a little difficult to understand.

Lets see another example:
greet ( name, cb ) {
  /** method implementations : if any **/
  cb ( 'Hello '+ name );
}

greet (  'Arun', function (msg){
  console.log ( msg );
});
The msg will be 'Hello Arun'. The idea is a callback is passed along with the function call. Inside the function after execution of method implementations, the call back is executed. We can use the return message inside our callback function.
Once this concept is clear,  it is very easy to expertise javaScript. 

For Web Developer

  open -a "Google Chrome" --args --disable-web-security