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:

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

sum(1 + 2); // 3
```

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?

```javascript
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()); // ?
```

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:

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

console.log(a); // { name: 1 }
```

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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction) gave us the answer:

```javascript
// 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);
```

_If you found this helpful, consider [subscribing to my newsletter](https://upweb.dev) for weekly web development insights and updates. Thanks for reading!_
