Blog

Functions in JavaScript

Functions in JavaScript bring out the real flexibility of the language. Functions can be stored in variables, defined at runtime. Even inbuilt functions can be redefined.
Declaring functions

function add(a,b)
{
return a+b;
}
a and b are the 2 parameters. I can call this function in the following way
add(3,4). a will become 3, and b will be 4. Answer will be 7.

What happens if I pass only one parameter. add(3).a will be 3, b will be undefined. Answer will be NaN.

Parameters Array
JavaScript creates an array of all parameters passed to a function. This can be used to access all parameters no matter how many are passed.
Consider the following example:

function add() {
var sum = 0;
for (var i = 0; i <= arguments.length – 1; i++)
sum = sum + arguments[i];
return sum;
}
Now, we can call this function as add(1,2,3,4). This will create an array arguments with the values {1,2,3,4}. The answer will be 10.

We can define a function and store it in a variable and then call it.

var x = function () {
var sum = 0;
for (var i = 0; i <= arguments.length – 1; i++)
sum = sum + arguments[i];
return sum;
};
var result = x(1,2,3,4); Answer 10.

Replacing x by the definition we get an anonymous function.

var result = function () {
var sum = 0;
for (var i = 0; i <= arguments.length – 1; i++)
sum = sum + arguments[i];
return sum;
}(1,2,3,4) ;
Answer is 10.

Finally, we can redefine the in built JavaScript functions as well.
For example the prompt function shows a message box with a textbox.

I can redefine the prompt function as

prompt = function () {
var sum = 0;
for (var i = 0; i <= arguments.length – 1; i++)
sum = sum + arguments[i];
return sum;
}
var result = prompt(1, 2, 3, 4);
Answer =10;

We can even redefine functions inside objects.
Thus the following will redefine Math.sqrt.

 

Math.sqrt = function () {
var sum = 0;
for (var i = 0; i <= arguments.length – 1; i++)
sum = sum + arguments[i];
return sum;
}
var result = Math.sqrt(1, 2, 3, 4); Answer will be 10 like before.
JavaScript is incredibly flexible. Unleash your creativity and enjoy.