Javascript Console
by Peter.
With all my recent Javascript experiments, I wanted a browser-independent Javascript console more and more. I found Rhino and have been using it for the last month or so. It’s proven pretty useful, and it was quite easy to install: I simply copied js.jar
to /usr/local/rhino/
and then added the following to my .profile
for convenience: alias js="java -jar /usr/local/rhino/js.jar"
I just learned about jsc, a console Apple includes with the JavascriptCore library that I believe every version of OS X has installed by default. It’s found at /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc
, so again you’re going to benefit from an alias or adding the directory to your PATH
.
While Rhino has more features, namely the ability to load Java libraries, the jsc
experience is better: the console strikes me as more responsive (it definitely launches much faster), a command history is available and you can use ctrl+a
and ctrl+e
to jump to the beginnings and ends of lines. Whoever made jsc
seems to have a functional bent, as every expression’s return value is printed out. This means you get undefined
on screen a lot if you’re doing lots of loops and/or prints, which can be annoying.
Update, 2010-06-22: Using rlwrap
(e.g. alias js="rlwrap java -jar /usr/local/rhino/js.jar"
) solves many of the problems I had with Rhino.
Speaking of that, I think they handle the return values of loops incorrectly. As I understand it, all loops should return undefined
, i.e. nothing. But consider this jsc
session:
> var a = 1; while (a < 4) { print(a); a++; } 1 2 3 3
3 is printed out twice because it is ‘returned’ by the while
loop. Of course, while
does not really return a value, as this session shows:
> var a = 0; var b = while (a < 4) { a++; } Exception: SyntaxError: Parse error
But where does the 3 come from, the a
variable or the loop’s condition? From the following sessions, I believe it comes from the last time the condition evaluates to true
:
> while (1 != 1) {} undefined > var a = 1; while (1 != 1) { a; } undefined var a = 1; while (1 != 1) { a = 2; } undefined > var a = 1; while (a != 2) { a = 2; } 2
Note that when the condition never is true, there is no defined value outputted. Likewise, assignment within the loop has no effect on what is ‘returned’. Or rather, I wish it was that way. Consider this:
> var a = 0; while (a < 2) { a = 2; } 2 > var a = 0; while (a < 2) { a++; } 1
To be honest, I really am confused about what jsc
is doing here. It seems wrong, though irrelevant since these values printed out cannot be assigned to a variable and used. Perhaps someone from the jsc
team can explain this?