#405💼 Interview💻 Code
What is the difference between Function constructor and function declaration
Advertisement
728x90
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
1var a = 100;
2
3function createFunction() {
4
5var a = 200;
6
7return new Function("return a;");
8}
9
10console.log(createFunction()()); // 100Function declaration:
javascript
1var a = 100;
2
3function createFunction() {
4
5var a = 200;
6
7return function func() {
8 return a;
9};
10}
11
12console.log(createFunction()()); // 200Advertisement
Responsive Ad
🎯 Practice NowRelated Challenge
JavaScript Coding Exercise 62
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement
728x90
405of476