FrontendDeveloper.in

JavaScript question detail

What is the difference between Function constructor and function declaration

The functions which are created with Function constructor do not create closures to their creation contexts but they are always created in the global scope. i.e, the function can access its own local variables and global scope variables only. Whereas function declarations can access outer function variables(closures) too.

Let's see this difference with an example,

Function Constructor:

var a = 100;
function createFunction() {
var a = 200;
return new Function("return a;");
}
console.log(createFunction()()); // 100

Function declaration:

var a = 100;
function createFunction() {
var a = 200;
return function func() {
return a;
};
}
console.log(createFunction()()); // 200
Back to all JavaScript questions
Get LinkedIn Premium at Rs 399