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().
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.
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.
`Function() is a faster and more secure alternative to eval().
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.
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.
-- 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With