0

So I posted this question Putting a simple expression language into java and got a great answer about using ScriptEngine to allow the user to write javascript which I did and it seemed to work

But whilst an expression like

(artist.length>0 ? artist + '-' :'') + (album.length>0 ? album + '-' :'')

works using a full if statement does not

if(artist.length>0) {artist + ':-'}   + (album.length>0 ? album + '-' :'') 

You might ask why Im doing this, well I was hoping I could use an if:else if:else statement and this was a step towards that

2
  • java != javascript ... Commented Jul 18, 2011 at 18:14
  • @Neal: The OP is asking about JS code that's being run from Java, using JSR-223. Sometimes this kind of context matters, hence why the OP mentioned it. Commented Jul 18, 2011 at 18:15

1 Answer 1

4

That simply isn't valid javascript. The

<cond> ? <iftrue> : <iffalse>

is the 'expression' form of if-else, and returns the value which can be used.

if {

} else {

}

is the 'statement' version, and is used to execute code, and does NOT return a value.

3
  • thanks you've exposed my javascript ignorance here, so is it possible for me to do the equivalent of if else if else in the expression Commented Jul 18, 2011 at 18:27
  • You could nest the expressions, like a ? b : (c ? d : e), which translates to: If a, then b, else if c, then d, else e Commented Jul 18, 2011 at 18:32
  • thanks that worked i.e (albumartist.length>0 ? albumartist :(artist.length>0 ? artist : ' ')) Commented Jul 18, 2011 at 18:44

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.