Nov
25
2015
By abernal
These are so called functions on the fly or anonymous functions, they are loaded at execution time
Syntax
var diffOfSquares = function (a, b) { return a*a - b*b; }
Executing a function expression
Sample
// The Function expression var sayHello = function () { console.log("Hello There buddy!"); }; // Pay attention with the semicolon // A call to a normal function writeSomething(sayHello); // The normal function declaration function writeSomething(message){ ... message(); // This will execute the anonymous function console.log(message); // This will print the function declaration ... }
Functions as paramenters
Sample
Functions can also be passed like parameters, the next sample ilustrates this aspect of functions
var function1 = function (input) { return (3 * input - 8); }; var function2 = function (input) { return ((input + 2)*(input + 2)*(input + 2)); }; var function3 = function (input) { return (input*input - 9); }; var function4 = function (input) { return (input % 4); }; var puzzlers = [function1, function2, function3, function4];
Functions can be returned from a function
Sample
var parkRides = [["Name 1", 40], ["Name 2",50], ["Name 3", 60]]; var fastPassQueue = ["Cedar Coaster", "Pines Plunge", "Birch Bumpers", "Pines Plunge"]; var wantsRide = "Cedar Coaster"; var ticket = buildTicket (parkRides, fastPassQueue, wantsRide); // Alternative call to buildTicket // buildTicket (parkRides, fastPassQueue, wantsRide)(); ticket(); function buildTicket (allRides, passRides, pick ) { if (passRides[0] == pick ){ var pass = passRides.shift(); return function () { alert("Hurry! You´ve got a Fast Pass to " + pass + "!"); }; } else { for(var i = 0; i < allRides.length; i++){ if(allRides[i][0] == pick){ return function () { alert("Hello There, A ticket is printing for :"+pick+"!\n"+ "Your wait is about "+allRides[i][1]+" minutes"); }; } } } }