DEV Community

Cover image for Difference Between new Function() and new function() in JavaScript
Zachary Lee
Zachary Lee

Posted on • Originally published at webdeveloper.beehiiv.com on

Difference Between new Function() and new function() in JavaScript

JavaScript is indeed flexible, but it also brings some confusion. For example, you can use multiple ways to do the same thing, such as creating functions, objects, etc. So what is the difference between the two mentioned in the title?


new Function is another way to create a function, its syntax:

const func = new Function ([arg1, arg2, ...argN], functionBody);

A simple example:

const sum = new Function('a', 'b', 'return a + b');

sum(1 + 2); // 3
Enter fullscreen mode Exit fullscreen mode

Well, this gives great flexibility. It’s not common, but there are some cases where it can be used. For example, we can use it when we need to dynamically compile a template into a function, which is what Vue.js does as far as I know. Besides that, it can also be used if we need to receive code strings from the server to create functions dynamically.

Let’s quickly talk about its features. See what the code below will output?

globalThis.a = 10;

function createFunction1() {
  const a = 20;
  return new Function('return a;');
}

function createFunction2() {
  const a = 20;
  function f() {
    return a;
  }
  return f;
}

const f1 = createFunction1();
console.log(f1()); // ?
const f2 = createFunction2();
console.log(f2()); // ?
Enter fullscreen mode Exit fullscreen mode

The answer is 10 and 20. This is because new Function always creates functions in the global scope. Only global variables and their own local variables can be accessed when running them.


Whereas new function() is intended to create a new object and apply an anonymous function as a constructor. Such as the following example:

const a = new (function () {
  this.name = 1;
})();

console.log(a); // { name: 1 }
Enter fullscreen mode Exit fullscreen mode

That’s it. Actually, every JavaScript function is a Function object, in other words, (function () {}).constructor === Function returns true.

An associated knowledge point is how to use new Function() to create an asynchronous function? MDN gave us the answer:

// Since `AsyncFunction` is not a global object, we need to get it manually:
const AsyncFunction = (async function () {}).constructor;

const fetchURL = new AsyncFunction('url', 'return await fetch(url);');

fetchURL('/')
  .then((res) => res.text())
  .then(console.log);
Enter fullscreen mode Exit fullscreen mode

If you found this helpful, please consider subscribing to my newsletter for more useful articles and tools about web development. Thanks for reading!

Top comments (0)