JavaScript/Shell

From Wikibooks, open books for an open world
Jump to navigation Jump to search



You can play around with JavaScript in one of multiple shells, in interactive batch mode. This means that you can enter JavaScript one line at a time and have it immediately executed; and if you enter a statement that returns a value without assigning the value anywhere, the value is displayed.

For a list of shells, see the mozilla.org list referenced from Enternal links.

Keywords: REPL.

Standalone[edit | edit source]

Mozilla Firefox uses SpiderMonkey JavaScript engine, which is available as a standalone interactive shell for multiple platforms. You can download it from:

Unzip the file, and run "js" from the command line. A prompt appears:

js>

You can enter statements, one at a time:

js> function incr(i) { return i+1; }
js> incr(1)
2
js> function plus2(i) {
return i+2;
}
js> plus2(1)
3
js> incr
function incr(i) { return i+1; }
js> print ("1+1:"+incr(1))
1+1:2
js> console.log("Yep.") // Console is available
Yep.

Multi-line function definitions can be entered one line at a time, pressing enter after each line.

To run JavaScript snippets that use alert function--since they are intended for web browsers, you can define your own alert function:

js> function alert(message) { print ("Alert: "+message); }

From browser[edit | edit source]

You can have an interactive mode, entering JavaScript one line at a time and have it immediately executed, directly from your web browser.

In many versions of Firefox, press Control + Shift + K to get a web console window. At the bottom of the console window, there is a separate one-line field into which you can enter JavaScript lines and have them run by pressing Enter. Even multi-line function definitions can be entered, but not by pressing Enter but rather Shift + Enter and pressing Enter only after the whole definition was entered.

External links[edit | edit source]