Java Script Functions and Closures

Finer Points

Java Script Functions and Closures

Java Script functions are fundamentally Objects belonging to global object. Java Script functions can be declared as variables. The syntax to write java Script functions is :

Function function_name ( parameter1, parameter2)
Function area( length, bredth) { }

1.’function’ is a reserved keyword, should not be used other than declaration of functions
2. The type of a Function is function typeof function(){} //Returns function

3 Ways of declaring Java Script Functions :

1.By Function Declaration
function sum( x, y)
{ return x + y ; }
document.getElementById(“demo”).innerHTML=sum(4,5);

2.By Function Expression Java script functions can also be defined as functions, which forms a part of expression syntax. In other words it is variable assignment.

A . Anonymous Function Expression

var sum = function(x, y)
{ return x + y};
document.getElementById(“demo”).innerHTML=sum(4,5);

B.Named Function Expression

function sum(x, y)
{ return x + y};
document.getElementById(“demo”).innerHTML=sum(4,5);

C. Self-invoking Function Expression
(function(){
document.getElementById(“demo”).innerHTML = 2 + 3;}
)();
Above 3 ways have their own significance and best practices to contribute for clean and robust web application development.


3. By Function Constructor

var sum=new function(“a”, ”b” , “return a + b” );
document.getElementById(“demo”).innerHTML=sum(4,5);

Peculiarities of Java script functions

  1. Empty Java script functions returns “ Undefined”

Like other programming languages the java script function syntax does not specify whether a function returns some value or not. Other languages ( c, c++, Java) use “void” keyword to notify if they do not return any value. The following code snippet returns “undefined”, even though it does not have any data to return:

function returnNothing()
{ return } alert( returnNothing() === undefined ) // true

2.Function Declarations are parsed, when browser prepares to executes the code a. Java Script Function declarations can be placed either before the function definition or after function definition as shown below:

1.Function definition before function declaration

hello(“Jasmine”)
function hello(name)
{ alert(“Hi, “+name) }

2.Function declaration before function definition

function hello(name)
{ alert(“Hi, “+name) }
hello(“Jasmine “)

3.Functions with same name and syntax overwrites, irrespective a condition is true or false

Both the codes execute to shows “Hello-2“ except in Fire Fox browser. I have tested in Chrome and Opera, works fine in both.

Snippet – 1

hello() if (true)
{ function hello(){ alert(“Hello – 1”) } }
else{ function hello(){ alert(“Hello-2”) } }

Snippet – 2

hello() function hello() { alert(“Hello – 1”)}
function hello(){ alert(“Hello-2 “) }

3.Functions are used for Prototype Creation of Objects
Java Script functions are very robust. Function being an attribute, which defines the behavior of an object, they co exist along with variables in the context of object. But on other hand java script functions are robust enough to define the attributes ( variables) and behavior( functions) of objects.

Check out the following code snippet to understand them better :

function car(brand_Name, car_Name, car_Price, car_Color)
{ this.BrandName = brand_Name; this.CarName = car_Name; this.CarPrice = car_Price; this.CarColor = car_Color; }
var myCar = new car(“Toyota”, “Etios”,800000, “red”);
var yourCar = new car(“Hyundai”, “Verna”, “900000, “Black”);

Java script Expressions Vs Java script Declarations

Java script functions are values, like variables function names hold the whole functions as its value. Run this code snippet to find what does it mean?
function iHold_value()
{ alert(1) }
document.write(iHold_value)
//alert(iHold_value)
In fact, java script function declaration are internally turned to java script expressions.

Self-Invoking Functions

Java script functions are versatile. In fact they are multipurpose, handy and highly flexible too.One such feature is self-invoking functions (SIF)in java script . They stand alone in whole bunch of code, but does the job for all along with other java script functions.As we browse through web pages, there are few page level scripts, they need to update page level information at regular intervals, like fetching a piece of data from data base are done by self-invoking functions at regular interval.

4 ways of declaring Java scripting self-invoking functions
All four variations mentioned below do the same job:

Type – 1

(function ()
{ document.getElementById(“demo”).innerHTML = 2 + 3;
document.write( 2 + 3 ) } ());
Type – 2
(function(){ document.getElementById(“demo”).innerHTML = 2 + 3;
document.write( 2 + 3 ) })();
Type – 3
void function(){ document.getElementById(“demo”).innerHTML = 2 + 3;
document.write( 2 + 3 )} ();
Type – 4
!function()
{ document.getElementById(“demo”).innerHTML = 2 + 3;
document.write( 2 + 3 ) }();
You can pass parameters to anonymous function as shown below:
(function area_square(length)
{ var area_of_sqaure= length * length; alert(area_of_sqaure);})(10); // 100

Why do we require self – Invoking functions?

1.Data Encapsulation and Name Collision at Global Name Space
Self-invoking java script functions extends the language capabilities by introducing an objected oriented concept called : Encapsulation. This helps to keep data not being exposed outside , there by local variables would not be accessed by any other functions for unwanted manipulation. One such situation is java script variable and function declaration hoisting. In the following example Self-invoking function has two variable is being private and not known to outside SIF scope.

(function (){ var week_days = [Sunday’,’Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’]
var day = new Date();
var day_name = “Welcome, today is ” + week_days [day.getDay()]
document.write(day_name); }
());

Above SIF encapsulates entire application logic, not being exposed to outside. On other hand, local variables remained private and confined to the lexical scope of anonymous function, without global name space being polluted with week_days, day_name references, which is unwanted.

2.One Time Initialization In certain situations you may require to initialize a web element like day reminder, visitor name or any other user experience enhancing elements, which is supposed to be executed at once during the session or at regular interval. The following code does every time once the page loads or reloads :

(function () { var week_days = [Sunday’,’Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’]

var day = new Date();
var day_name = “Welcome, today is ” + week_days [day.getDay()]
document.write(day_name); }
());

Function Hoisting

Java script hoisting is automatic elevation of all function declarations to global space, no matter where ever they are declared in the code. By hoisting to global space these declaration would be visible to entire code. Functions Hoisting enables calling or invoking a function before its declaration, as shown in following code snippet.
Code Snippet – 1

document.write(multiply(5));
function multiply(x){
return x * x; };

Code Snippet – 2
document.write(what_is_ur_name());
function what_is_ur_name(){
return “Function Hoist”; }
Note : Like functions, declared variables also hoisted to global space.

Functions and Variable Scope

Java script functions and variables exist in “Lexical Environment”. The lexical environment is of two kinds: Local Lexical Environment and Global Lexical Environment. Global Lexical Environment is Window Object, where all global variables and functions exist and Local Lexical Environment is function level scope, where all local variable and function exist. In java script, functions and variables share a special relation, where variables exist in a function level scope. In other words, the variables declared once in the function, has the visibility or its existence across the function. Unlike other programming languages java script does not have block level scope.
The Caveat :
Variables declared globally is known across the program or code, it can be accessed any where from the program. Variables declared with in the function scope is known across the function and can’t be accessed outside the function.

var name = ‘Robert’;
// variable is global

function showGlobalName() {
alert(name);
// uses the global name
}
showGlobalName();
// =>Robert

function showLocalName(){
var name = ‘Rex’;
// name is local, hides the global name
alert(name);
}
showLocalName();
// => Rex

function showArgument(name){
alert(name);
// arguments are locally scoped => Rita
}
showArgument(‘Rita’);

Function and Variable : An anatomy Execution Environment of java script functions – what goes behind the scene ?

When functions are called a Lexical Enviroment along with ReadRecord Environment created. When following function prepare to execute, java script execution engine creates the Lexical Environment  by populating arguments, variables and nested function variables. This  Function Lexical environment  object is internally used to read and write the data , and not accessible as Global Lexical Environment Object.

function showName(name){
var str = “Hello,” + ‘name’; // not block level scoped
alert(name); // variable name is available outside the if block
}
showName(‘john’);

When interpreter prepares for executing an empty Lexical Environment object is created with arguments and local variables. Function declarations are initialized before code is executed. Hence, the first line of the code is evaluated to window = [showName : function]
function showName(name){
Lexical Environment : [ name: james, str = undefined]
var str = “Hello,” + ‘name’; // not block level scoped
alert(name);// variable name is available outside the if block
}
showName(‘james’);

Arguments have value assigned , local variables are instantiated to ‘Undefined’ 2.When function code runs, assignments are done. function showName(name){ Lexical Environment : [ name: james,  str = undefined] var str = “Hello,” +  ‘name’; Lexical Environment : [ name: james,  str = “Hi James”] alert(name); } showName(‘james’); The alert looks for name in Lexical Environment The caveat : Variables are instantiated in the preprocess stage, assignments happen at execution time. This  Function Lexical environment  object is internally used to read and write the data , and not accessible as Global Lexical Environment Object.

Java script Nested Functions and Closure

Like other programming languages java script supports, nesting the function with in a function. Functions being nested share a Function Level Scoping, which enables inner functions to access outer function variables and arguments directly. Interestingly, the inner functions play major role in establishing nested relationship with outer functions. Inner functions references to their parental outer function Lexical Environment to form a chain of lexical environment inside out.

var num = 1;
function showNum(){ document.writeln(num + “<br>”);
function showIncrement()
{ num++; document.writeln(num + “<br>”); }
showIncrement() }
showNum()

Java Script Nested Functions and Closure

In the pre execution stage , the function showNum() is evaluated and its lexical environment is set in global environment scope as shown below :

var num = 1;
function showNum(){ document.write(num + “<br>”);
window = [function: showNum, a: undefined],
Also it creates a reference or a hidden property [[scope]], this hidden property holds the reference to global window object.
Note :

1.Nested functions can access variables and functions (members) of outer function. On other hand inner functions members can’t be accessed by outer function.

2.Inner functions inherit all variables and arguments in outer function. Inheritance is possible because the inner function has complete reference of outer function scope as shown in the above diagram.

Java script Closures

Java Script closure are a special kind of functions ,which result in creation of a special object, which holds all functions and variables created in the specific environment in which it was created. I know this is a most complicated definition.
Java Script Closures

Jack and Jim are assigned to ring the bell. They both ring the same bell, but the count is incremented for Jack and Jim separately.

bell() function works like a factory, where in jim_Rings() and    jack_Rings() invoke the bell() function by taking the function reference by assigning as shown below: var jim_Rings  = bell(); var jack_Rings()  = bell();

Each time the bell() function is invoked , it executes the inner function rings() and returns the count. Here, the bell() is invoked by jim_Rings() and  jack_Rings() in separate function calls and they get their own copy of the object, in which function call specific data (count) is stored. As shown in the above diagram the the bell() function executes and spans into separate processed objects.

Check out the following code snippet, in which inner function forms a closure, where in you can pass arguments for outer and inner function. The inner function refers to outer function argument and process the data defined with in its inner function scope.

Check out the following code snippet, in which inner function forms a closure, where in you can pass arguments for outer and inner function. The inner function refers to outer function argument and process the data defined with in its inner function scope.

function outside(x) {
function inside(y) {
return x + y;
}
return inside;
}
fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it
result1 = fn_inside(5); // returns 8
result2 = outside(3)(5); // returns 8

Function Precedence and name conflict.

In nested functions the inner function has highest precedence over outer function. To demonstrate this check out following code snippet:

function outside() {
var x = 10;
function inside(x) {
return x;
}
return inside;
}
result = outside()(20); // returns 20 instead of 10

when argument is passed, the function inside() takes the highest precedence and returns 20 as shown in the code snippet. On other hand, an interesting fact is that var x is used in both outside() and inside() function scopes, even though variable name is same, the variable x  insde() function takes the highest precedence.