0

Can anyone explain me why the following Java code which executes the JavaScript return "Smith" here?

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    String jsSnippet = "var fullName = 'Joe Smith'; fullName.substring(fullName.indexOf(' ') + 1);";
    System.out.println(engine.eval(jsSnippet));

Similar JavaScript code (jsFiddle) which gives the same output as above Java code is

var jsSnippet = "var fullName = 'Joe Smith'; fullName.substring(fullName.indexOf(' ') + 1);";
document.write(eval(jsSnippet));

PS: I know eval is evil, but this is one of the circumstances I have to use JavaScript eval.

3
  • What exactly is the issue? A return value of Smith is what I would expect from the JS you have. Commented Jan 14, 2013 at 6:14
  • The question is unclear. You have 2 snippets of identical JS, and you say they both return the same value. What's the problem? Commented Jan 14, 2013 at 6:14
  • @broofa & Alex - There is no problem in the JS code, but I have not added any return statement in the eval, then why does the eval return the "Smith". And why it doesn't work if I add return statement in eval? jsfiddle.net/hs2501/xaJg4/2 Commented Jan 14, 2013 at 18:02

1 Answer 1

2

The eval function evaluates the last expression passed into it, and returns its value. See the relevant section on eval at the Mozilla Developer Network.

Sign up to request clarification or add additional context in comments.

3 Comments

I have not added any return statement in the eval, then why does the eval return the "Smith". And why it doesn't work if I add return statement in eval? jsfiddle.net/hs2501/xaJg4/2
Oh, the last expression is implicitly returned. Couldn't work out what you were asking, but there's your answer.
@Hemant, here's the relevant explanation of eval from the Mozilla Developer Network: developer.mozilla.org/en-US/docs/JavaScript/Reference/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.