How to write JavaScript functions in different styles

INTENT
=================================================================
This article is to explore different ways to write JavaScript functions. All example below are in context of plain JavaScript and do not depend on any library like JQuery (which might come as a surprise to few :)
Level: Beginners

Original Basic implementation.. Declare a method and call at some point later
function SayHello(msg) {
alert(msg);
}
//call explicitly
SayHello('my name is'); //alerts "my name is"

Different style where function is assigned to a variable and then called later
var SayHello = function(name) {
alert(name);
};
SayHello('Deepak');

NOTE: Check the ; at end of function (i.e. after }). This was not required in previous example because we declared a method. However, now we are assigning a function to a variable just like we say var i = 10;
If you miss this ';', function would still execute properly but many IDE's may complain that code is not properly structured.

Simple function. Self executed automatically...

var SayHello = function(name) {
alert(name);
}('Aggarwal');

Method is called once automatically and the result is set to SayHello.
IMPORTANT: SayHello is no longer a function. Any attempt to call it later as SayHello() would result in an exception: Uncaught TypeError: Property 'SayHello' of object [object Window] is not a function
This is a good approach when you wish to execute any method once. If you do not want any result, you can even do so without a name (ANONYMOUS FUNCTIONS) as shown below:
 (function(){
alert("i've no name");
})();
As mentioned above, When a method is called in self-executing style, it executes once and the result is stored. Everytime it is called the same result displays.
     var r = 1;
var multiply = function (x, y) {
r = r * x * y;
return r;
} (2, 3);

//Internally, it is now like: var multiple = 6;
alert(multiply); //alerts 6
alert(multiply); //alerts 6 (and not 9 if you thought 6*2*3)
alert(multiply(5,7)) //ERROR:Uncaught TypeError: Property 'multiply' of object [object Window] is not a function .... Forgot?? Now it is var multiply = 6;

A function can optionally be wrapped in brackets (Semantic purpose only)
var multiply = (function(x,y) {
return x*y;
}) (2,3);
A function can be declared to have multiple return methods


var calculator = function (x, y) {
return {
add: function () { return x + y; },
subtract: function () { return x - y; },
multiply: function () { return x * y; },
divide: function () { return x / y; },
staticresut:12
};
};

alert(calculator(3, 3).add()); //returns 6
alert(calculator(3, 3).subtract()); //returns 0
alert(calculator(3, 3).multiply()); //returns 9
alert(calculator(3, 3).divide()); //returns 1
alert(calculator(3, 3).staticresult); //returns 12
alert(calculator(3, 3).add); // alerts "function () { return x + y; }" Anonymous function
var myAddMethod = calculator(3, 3).add;
alert(myAddMethod()); // alerts 6

NOTE: If you don't use () with function name, you will get the function text instead. For example say "calculator(3, 3).add" will return "function () { return x + y; }" However, you can execute any JavaScript code by setting it to a variable and later calling it with () as in last 2 lines above.

NOTE: If you use this approach i.e. having multiple return options, you CAN NOT have a default return. So, you can not have Calculator(3,3) only to return some default.


Methods with internal support system
var greeting = function () {
var greetings = {
day: 'good afternoon',
morning: 'good morning',
evening: 'good evening'
};

var calculatGreeting = function () {
var currentHour = new Date().getHours();

if (currentHour < 12)
return greetings.morning;
else if (currentHour <= 15)
return greetings.day;
else
return greetings.evening;
};

return calculatGreeting(); //alerts greeting based on current hour
};

alert(greeting()); //internall calls calculateGreeting()
alert(greeting.greetings.day) //error: it is not accessible outside function
greeting.calculateGreeting() //error: it is not defined as a returned function
Methods can have more methods, variables, structures {} in definition. However, All these internally accessible only.

NOTE: This example also highlights that a function inside another function can access variables/functions of parent function.

Comments

Popular posts from this blog

How to construct a B+ tree with example

How to show only month and year fields in android Date-picker?

Visitor Counter Script Using PHP