Function declaration , expression & constructor
Notes:
3. Function Constructor
Functions are defined using new keyword and Function() constructor.
Syntax: /* definition of function */
var functionName = new Function(“param1”,”param2”,…. ,“function body”);
Ex: /*a function without parameters, without returning value*/
var wishHi = new Function(“{document.write(‘Hi’);}”);
Syntax: /* function call */
functionName([parameters list]);
Ex:
wishHi();
Example Code:
/* function defined using function declaration */
function wishHi()
{
document.write("Hi","<br/>");
}
wishHi();
/* function defined using function expression */
var wishHi = function()
{
document.write("Hi","<br/>");
};
wishHi();
/* function defined using function constructor */
var wishHi = new Function("{document.write('Hi','<br/>');}");
wishHi();
/* function defined using function declaration */
function add(num1,num2)
{
return num1+num2;
}
document.write(add(2,3));
/* function defined using function expression */
var add = function(num1,num2)
{
return num1 +num2;
};
document.write(add(2,3));
/* function defined using function constructor */
var add = new Function("num1","num2","{return num1 +num2;}");
document.write(add(2,3));
/* How to continue string to the Nextline using \ */
var add = new Function("num1","num2","{\
return num1 +num2;\
}");
document.write(add(2,3));
Interview Questions: