Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last evaluated expression in Javascript

Tags:

javascript

Is it possible in Javascript to get the result of the last evaluated expression? For example:

var a = 3;
var b = 5;
a * b;
console.log(lastEvaluatedExpression); // should print 15

So it would be something like eval() where it returns the last evaluated expression, but I cannot use eval().

like image 830
dgaviola Avatar asked May 27 '14 19:05

dgaviola


People also ask

How are expressions evaluated in JavaScript?

JavaScript eval() The eval() method evaluates or executes an argument. If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.

What does eval (' VAR B 3 do in JavaScript?

The eval() function in JavaScript is used to evaluate the expression. It is JavaScirpt's global function, which evaluates the specified string as JavaScript code and executes it. The parameter of the eval() function is a string. If the parameter represents the statements, eval() evaluates the statements.

Which is faster eval () or new function?

`Function() is a faster and more secure alternative to eval().

What does => mean in JavaScript?

It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.


2 Answers

There is no standard, reified concept of "the result of the last evaluated expression" in JavaScript. There are actually not too many languages that do have such a thing. Various JavaScript REPLs may provide some facility along these lines, but that's specific to those REPLs. Therei s no general "JavaScript" way.

like image 168
Chuck Avatar answered Oct 22 '22 05:10

Chuck


-- package.json --

  "dependencies": {
    "stream-buffers": "^3.0.1"
  },

-- main.js --

const streamBuffers = require('stream-buffers');

const repl = require('repl');
const reader = new streamBuffers.ReadableStreamBuffer();
const writer = new streamBuffers.WritableStreamBuffer();

const r = repl.start({
    input: reader, 
    output: writer,
    writer: function (output) {
        console.log(output)
        return output;
    }
});
reader.push(`
var a = 3;
var b = 5;
a * b;`);
reader.stop();

-- output --

undefined
undefined
15

see: https://nodejs.org/api/repl.html

like image 39
zswang Avatar answered Oct 22 '22 05:10

zswang