Last evaluated expression in Javascript
Asked Answered
G

4

11

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().

Gibberish answered 27/5, 2014 at 19:21 Comment(16)
This is not possible.Zambia
The question is, why do you want to do this?Formwork
@RocketHazmat can you explain why? I'm kind of curiousSeicento
@RUJordan: Because unless you were to write your own JavaScript interpreter, there is no way to get the "last evaluated expression". Unless I am not understanding the question.Zambia
Preserving this link because not full answer but really handy: developer.chrome.com/devtools/docs/commandline-api#_Seicento
@RUJordan: Hmm... didn't know about that. Though it looks to only work in Chrome and only in its DevTools ("Command Line API is only available from within the console itself").Zambia
@RocketHazmat correct. They're handy and related, but not what the OP probably wants.Seicento
@LeeTaylor: I have like Javascript templates that are filled with snippets of code the user writes. Those snippets are the body of functions but I want the user to be able to write 'a * b' instead of 'return a * b'. Notice that you cannot simple add 'return' because the expression might be more complex and could contain several statements.Gibberish
@dgaviola: You can use an AST transformer such as github.com/benjamn/recast and convert the last expression statement to a return statement. Shouldn't be too difficult.Coastal
@Gibberish you should update your question to explain what you really want to achieve "the big picture"Aeneas
@FelixKling I think I will need to do something like that. ThanksGibberish
Recast builds on top of Esprima, which has a simple online demo which is valuable to find out to which AST some piece of code is converted: esprima.org/demo/parse.html. The the interface of the AST nodes created is explained in developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/…. It might take a bit to get your head around, but it's an interesting topic. Recast makes it very easy to modify the AST. I just don't know if a browser version is available. If not, you'll probably find another similar tool now that you know what to look for.Coastal
@FelixKling I have to do it on server side, but as I use Java I will use Rhino to modify the expressions (which parse code and builds the AST and it is what I'm using to run Javascript on server side). Now I need to figure out the patterns to modify the code correctly.Gibberish
Alright then, just wanted to provide some additional info :) Good luck!Coastal
@FelixKling It was very useful, thanks. Looking at the AST parser of Esprima I think the easiest way to achieve this is by declaring a variable before the snippet, then in the snippet, for all ExpressionStatments, modify them so the result is stored in the variable. Then, at the end of the script I will return that variable, which should contain the value of the last executed expression statement.Gibberish
@LoïcFaure-Lacroix I created a new question: #23919803. I think this one is still useful for someone that just wants to know if it is possible to get the last evaluated expression value in Javascript. Also I wrote the solution I found for my problem if anyone finds it useful.Gibberish
F
3

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.

Fetlock answered 27/5, 2014 at 19:33 Comment(0)
S
1

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

Skeptical answered 5/8, 2017 at 15:38 Comment(0)
C
0

This is not possible in javascript. The only way I can think of right now (that doesn't involve writing a new interpreter) is to use Coffeescript. Coffeescript automatically returns the last expression.

http://coffeescript.org/

http://coffeescript.org/extras/coffee-script.js

That includes functions such as Coffeescript.compile and Coffeescript.eval.

Cornia answered 27/5, 2014 at 19:39 Comment(1)
Well, using Elm or Fay or Scala.js or ClojureScript or any number of other expression-based languages would work as well.Fetlock
B
-3

There is no standard call for the last evaluated expression. No you would need to store values. For example you could do it like this:

var a = 3;
var b = 5;
var c = a * b;
var consoleResult = c.toString();
console.log(consoleResult); // should print 15
   //Then make your program logic change the value of consoleResult, as needed.  
Blister answered 27/5, 2014 at 20:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.