Lesson guide

Learning objectives

  • Explain the main purpose of The "new Function" syntax in JavaScript.
  • Identify the syntax, APIs, or concepts introduced in this lesson.
  • Use the examples to predict how JavaScript will behave before you run similar code.
  • Connect this topic to nearby lessons in Advanced working with functions.

Real-world context

This lesson matters when you need to recognize where The "new Function" syntax fits into real JavaScript programs. There’s one more way to create a function.

Key ideas

  • The "new Function" syntax is part of the Advanced working with functions chapter, so it builds on the surrounding concepts rather than standing alone.
  • Read each code example in two passes: first for the result, then for the rule that explains the result.
  • When a section compares similar features, focus on the condition that makes you choose one feature over another.

Key terms

  • The "new Function" syntax
  • new
  • Function
  • syntax
  • Advanced working with functions

There’s one more way to create a function. It’s rarely used, but sometimes there’s no alternative.

Syntax

The syntax for creating a function:

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

The function is created with the arguments arg1...argN and the given functionBody.

It’s easier to understand by looking at an example. Here’s a function with two arguments:

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

alert( sum(1, 2) );

And here there’s a function without arguments, with only the function body:

javascript
let sayHi = new Function('alert("Hello")');

sayHi(); // Hello

The major difference from other ways we’ve seen is that the function is created literally from a string, that is passed at run time.

All previous declarations required us, programmers, to write the function code in the script.

But new Function allows to turn any string into a function. For example, we can receive a new function from a server and then execute it:

javascript
let str = ... receive the code from a server dynamically ...

let func = new Function(str);
func();

It is used in very specific cases, like when we receive code from a server, or to dynamically compile a function from a template, in complex web-applications.

Closure

Usually, a function remembers where it was born in the special property [[Environment]]. It references the Lexical Environment from where it’s created (we covered that in the chapter Variable scope, closure).

But when a function is created using new Function, its [[Environment]] is set to reference not the current Lexical Environment, but the global one.

So, such function doesn’t have access to outer variables, only to the global ones.

javascript
function getFunc() {
  let value = "test";

  let func = new Function('alert(value)');

  return func;
}

getFunc()(); // error: value is not defined

Compare it with the regular behavior:

javascript
function getFunc() {
  let value = "test";

  let func = function() { alert(value); };

  return func;
}

getFunc()(); // "test", from the Lexical Environment of getFunc

This special feature of new Function looks strange, but appears very useful in practice.

Imagine that we must create a function from a string. The code of that function is not known at the time of writing the script (that’s why we don’t use regular functions), but will be known in the process of execution. We may receive it from the server or from another source.

Our new function needs to interact with the main script.

What if it could access the outer variables?

The problem is that before JavaScript is published to production, it’s compressed using a minifier – a special program that shrinks code by removing extra comments, spaces and – what’s important, renames local variables into shorter ones.

For instance, if a function has let userName, minifier replaces it with let a (or another letter if this one is occupied), and does it everywhere. That’s usually a safe thing to do, because the variable is local, nothing outside the function can access it. And inside the function, minifier replaces every mention of it. Minifiers are smart, they analyze the code structure, so they don’t break anything. They’re not just a dumb find-and-replace.

So if new Function had access to outer variables, it would be unable to find renamed userName.

If new Function had access to outer variables, it would have problems with minifiers.

Besides, such code would be architecturally bad and prone to errors.

To pass something to a function, created as new Function, we should use its arguments.

Common mistakes

  • Skipping the small examples and then missing the exact rule that The "new Function" syntax depends on.
  • Copying code without changing one value at a time to see which part controls the result.
  • Treating similar-looking syntax or APIs as interchangeable before checking their edge cases.

Summary

The syntax:

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

For historical reasons, arguments can also be given as a comma-separated list.

These three declarations mean the same:

javascript
new Function('a', 'b', 'return a + b'); // basic syntax
new Function('a,b', 'return a + b'); // comma-separated
new Function('a , b', 'return a + b'); // comma-separated with spaces

Functions created with new Function, have [[Environment]] referencing the global Lexical Environment, not the outer one. Hence, they cannot use outer variables. But that’s actually good, because it insures us from errors. Passing parameters explicitly is a much better method architecturally and causes no problems with minifiers.

Predict

Before running this new Function check, predict the four output lines. It compares generated parameters with an outer lexical variable.

javascript
Reveal explanation

The output is 5, 6, 20, and ReferenceError. new Function creates a function from strings, so its parameters must be declared explicitly in those strings. Both "a", "b" and "a,b" define two parameters. Passing outer as the value argument works because the generated function receives it explicitly. But readOuter cannot close over the local outer variable, because functions created with new Function use the global lexical environment, not the surrounding local one.

Try it

Change new Function("return outer") to new Function("outer", "return outer") and call it with outer. Predict the fourth output line.

Practice

  • Rewrite one example from this lesson without looking at the original, then run it and compare the result.
  • Change one input, operator, method call, or option in a code sample and predict what will happen before running it.
  • Explain The "new Function" syntax in your own words as if you were reviewing it with another learner.

Keep learning

Continue with Scheduling: setTimeout and setInterval when you are ready for the next lesson.