User Name:


User Email:




This information will only be saved for the purposes of communicating with those who have provided this information voluntarily regarding our services.We will never sell your name or email address to anyone.
© 2017 - First Crazy Developer (Abhishek Kumar)
  

crazydeveloper JavaScript Function - Part 2

Functions in JavaScript

  • Declarations can appear in function body
Local variables, “inner” functions
  • Parameter passing
Basic types passed by value, objects by reference
  • Call can supply any number of arguments
functionname.length : # of arguments in definition
functionname.arguments.length : # args in call
  • “Anonymous” functions (expressions for functions)
(function (x,y) {return x+y}) (2,3);
  • Closures and Curried functions

function CurAdd(x){ return function(y){return x+y} };

 

Function Examples

  • Anonymous functions make great callbacks

setTimeout(function() { alert("done"); }, 10000)

  • Curried function

function CurriedAdd(x){ return function(y){ return x+y} };

g = CurriedAdd(2);

g(3)

  • Variable number of arguments

function sumAll() {

   var total=0;

   for (var i=0; i< sumAll.arguments.length; i++)

           total+=sumAll.arguments[i];

   return(total); }

sumAll(3,5,3,5,3,2,6)

 

Use of anonymous functions

 

  • Anonymous functions very useful for callbacks

setTimeout(function() { alert("done"); }, 10000)

// putting alert("done") in function delays evaluation until call

  • Simulate blocks by function definition and call

var u = { a:1, b:2 }

var v = { a:3, b:4 }

(function (x,y) {

      var tempA = x.a; var tempB =x.b;  //local variables

      x.a=y.a; x.b=y.b;

      y.a=tempA; y.b=tempB

}) (u,v)

// This works because objects are passed by reference

 

Usage of Nested Functions to simulate a where clause in LINQ

 

customers.where = function (f) {
                            var filteredCustomers = new Array();
                            for (var i = 0 ; i <= this.length - 1; i++) {
                                if (f(this[i])) {
                                    filteredCustomers.push(this[i]);
                                }
                            }
                            return filteredCustomers;
                        };
 
                        var answer = customers.where(function (customer) {
                            if (customer.age > 22) {
                                return true;
                            }
                            else {
                                return false;
                            }
                        });
 
 
Thanks
Abhishek 

crazydeveloper Home Page 28 January 2017

Become a Fan