Skip to main content

The "new Function" syntax

 

The "new Function" syntax

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:

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:

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

alert( sum(1, 2) ); // 3

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

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:

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.

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:

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.

Summary

The syntax:

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:

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.

Comments

Popular posts from this blog

How to earn money off playstore

https://static1.freebitco.in/banners/728x90-3.png https://static1.freebitco.in/banners/728x90-3.png Earn How to build and grow your app's revenue streams Implement the right monetization strategy Choose the right monetization model Learn about the monetization options available on Google Play and combine them into a strategy that maximizes your app’s revenue. Sell in-app digital goods with Play billing Enhance the revenue from your free-to-download or ad-funded apps by selling durable or consumable digital goods. Sell subscriptions with Play billing Generate a more regular revenue stream from your app by selling access to content or features using subscriptions. Sell goods and services with Google Pay Simplify and streamline your e-commerce purchase funnel using Google Pay to let users buy with their credit or debit cards. Get paid to show ads with Google AdMob Show users ads from over 1 million Google advertisers, ads that fit right in with your app, using Google AdMo...

It’s the season finale of Nigerian Idol Season 6 this Sunday

  On Sunday, July 11, 2021, the winner of Nigerian Idol season 6 will be announced at a special season finale event live on DStv and GOtv. After weeks of watching the Top 11 contestants sing their hearts out on the live shows to earn the fans' votes, the competition is down to two finalists – Kingdom and Francis – vying for the number one spot! In addition to the finale spectacular, there will be surprise performances and other memorable moments. The winner of Nigerian Idol season 6 will win a recording deal of a six track EP, with music video shoots for three of the songs, and over 50 million Naira worth of prizes which include a N30 million cash prize and a brand new SUV. Other prizes include a BIGI branded refrigerator and one year supply of BIGI soft drinks from Rites Food Limited, an all-expense paid trip to Seychelles and a wide range of TECNO products, a weekend getaway package to Dubai for two from TravelBeta and a DStv Explora fully installed with a 12-month DStv Premium s...

Gram Free Review: How to make money online On Gram free

What is Gram Free? Telegram, one of the fast growing social network industry has unveiled their digital currency which is known as  Gram . The  Gram Free  is  a cryptocurrency based on a Ton blockchain platform developed by Telegram. A feature of  Gram is  the high speed of transactions. Cryptocurrencies implemented early blockchain platform due to the low speed of transactions  are more suitable for investment than for use as a payment tool, GramFree  is  also a ‘Get paid To’ website that rewards users with ‘grams’. On a ‘Get Paid To’, or GPT website, users  are  given currency in exchange for doing simple tasks. Usually, this includes buying stuffs from affiliate retailers, inviting new users into the program and sharing things on social media. Is Gram Free Legit? Yes Gram free is legit, Gram free is owned by the Telegram Company, Making the Gram free website trusted and reliable, you earn without investing a dime, the...