Gaurav Aggarwal Gaurav Aggarwal - 9 months ago 23
Javascript Question

Difference between function() and new Function()

while searching around the internet i found two ways of writing javascript function.

One is


var myFunction = new Function("a", "b", "return a * b");

var x = myFunction(4, 3);

Second is simple defining function

var myFunction = function (a, b) {return a * b};

var x = myFunction(4, 3);

When i used above both method i found no difference between these 2.

Is there any difference between these 2 or is there any use of using function constructor??


Object-Oriented JavaScript - Second Edition: When using the Function() constructor, you pass the parameter names first (as strings) and then the source code for the body of the function (again as a string). The JavaScript engine needs to evaluate the source code you pass and create the new function for you. This source code evaluation suffers from the same drawbacks as the eval() function, so defining functions using the Function() constructor should be avoided when possible.

 var first = new Function(
     'a, b, c, d',
     'return arguments;'

 first(1, 2, 3, 4); // [1, 2, 3, 4]

 var second = new Function(
     'a, b, c',
     'return arguments;'

 second(1, 2, 3, 4); // [1, 2, 3, 4]

 var third = new Function(
     'return arguments;'

 third(1, 2, 3, 4); // [1, 2, 3, 4]

Best practice: Do not use the Function() constructor. As with eval() and setTimeout(), always try to stay away from passing JavaScript code as a string.

What is the difference? See @Greg's answer