Functions as Arguments and Functions on Objects – Functional Programming in Javascript Part 2

tn500w_javascript-logo

Functions as Arguments and Functions on Objects – Functional Programming in Javascript Part 2

Functions as values is a concept of Functional programming, a variable pointing to a function. Well of course you can pass this variable around. Anything that you can do to a value, you can do it with function, as function is a value. Likewise we can pass the value as an argument to a function, similarly we can pass a function as an argument to a function.

var fn = function(){
   console.log("Hello");
}

var executor = function(fn){
   fn();
}

executor();

Any guesses for output! Well ofcourse, Hello.

Now, we all know the difference of object creation in Javascript with those in other languages. There is no class based schema(i.e. member variables and member functions). Anything that can be assigned to a variable can also be assigned to object property. Till now we have been knowing that object properties can contain primitive data types or objects too. Yeah you guessed it right, that since object property can be assigned to anything, well that includes functions. So with this we can say the objects in Javascript can contain primitive data types, objects, functions.

var myObj = {
 "prop1":true,
 "prop2":"anoop",
 "prop3":null,
 "prop4":{"objProp1":1},
 "myMethod":function(){
           console.log("Function in object");
         }
};

myObj.myMethod();

About Anoop Kumar Rai