joaner
joaner

Reputation: 716

get return value of last expression

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?

Upvotes: 3

Views: 342

Answers (2)

Harun Diluka Heshan
Harun Diluka Heshan

Reputation: 1256

Use eval(expression) instead like this:

console.log(eval("1+1; 1+2"));

Upvotes: 1

Nisarg Shah
Nisarg Shah

Reputation: 14541

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);

Upvotes: 4

Related Questions