3

On the Chrome console, you can get the return value of the last expression

> 1+1; 2+1;
< 3

How to implement this function in javascript?

$expressions = '1+1; 2+1;' // from user input
new Function($expressions).call() // return 3, not 2

Can only be inserted in the last expression return statement?

joaner
  • 706
  • 1
  • 5
  • 17
  • 1
    The console is giving you the result of the last statement, which is the program result, and which is something you can't directly access in JS. –  Mar 03 '18 at 14:05

2 Answers2

4

You could use eval, but keep in mind that it is not a good practice to use it.

var value = eval("1+1; 2+1;");

console.log(value);
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • 1
    The OP is already evaluating the code with `Function`, so `eval` isn't really any worse. Main difference is that `eval` can access local variables. So `eval` isn't much worse than evaluating any other code, like with ` –  Mar 03 '18 at 14:11
1

Use eval(expression) instead like this:

console.log(eval("1+1; 1+2"));
Harun Diluka Heshan
  • 1,155
  • 2
  • 18
  • 30