Skip to main content
InterviewHubPRO
Section Overview
Q409

Question 409 of 536

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

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

What is the difference between Function constructor and function declaration

senior LevelCode ExampleMemory Management

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