Function with new keyword #10daysUnknownJSChallenge #day4

Did you used a new keyword anywhere in the function?. Did you heard anytime before?. Yes, it exists. Let's explore a little bit about it. We often use functions in JavaScript and function is internally an Object. Typical function usage will look like below

This article is part of my #10daysUnknownJSChallenge where I spent a very little time to explore 10 unknown topics for the series of 10 days

Typical function usage in JavaScript

function getName(){
	return this.name;
}
// OR
const getName = function () {
	return this.name
}
// OR (ES6)
const getName = () => {
	return this.name
}

Syntax

new Function([arg1, agr2, ...argN],functionBody);

Here, functionBody must be a string which should be comprising the function definition.

Example

let add= new Function('a', 'b', 'return a + b');
console.log(add(1, 2)); // 3

Notes

  1. The functionBody executes in the global scope

Usage

As far as know, the usage could be calling a function in the script dynamically (may be based on some response from server-side)

Cautions

The modern JavaScript code often minified to reduce the file size. During the minification process, minifier, renames the variable name to smaller length names safely. Since we are passing function expression as a string to new Function, minifiers can't rename the variable inside it and causes an error