Can someone explain why these 2 functions behave differently.
Snippet 1:
function operate1(operator) {
return function(x, y) {
return x + operator + y;
}
}
Snippet 2:
function operate2(operator) {
return new Function("x", "y", "return x " + operator + " y;");
}
Usage:
adder1 = operate1("+");
adder2 = operate2("+");
adder1(5, 3); // returns "5+3"
adder2(5, 3); // returns 8
I am particularly curious of why operate2
evaluated the arithmetic expression when I thought it would evaluate it as a string at first glance. Does this have something to do with it being defined as a Function Object with the new operator?