InterviewHubPRO
Section Overview
Q409

Question 409 of 521

Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)

79%
JavaScript Internals (521 Qs)•Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)

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:

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

Function declaration:

javascript
 var a = 100;
 function createFunction() {
   var a = 200;
   return function func() {
     return a;
   };
 }
 console.log(createFunction()()); // 200