Conveniently start a JavaScript shell (jsc) on macOS

For one of my projects I wanted an easy way to try JavaScript on a command line (similar to pry or irb in Ruby). Here’s how I found out where the program is located and how to set up my Mac to conveniently start it.

1. Find out where jsc is located on the machine:

$ find / -name jsc -type f 2>/dev/null
/System/iOSSupport/…/JavaScriptCore.framework/Versions/A/Helpers/jsc
/System/…/JavaScriptCore.framework/Versions/A/Helpers/jsc
/System/Volumes/Data/…/JavaScriptCore.framework/Versions/A/Helpers/jsc
/System/Volumes/Data/…/JavaScriptCore.framework/Versions/A/Helpers/jsc    

Searching from the root folder may be a bit excessive, though. You may consider a more limited search.

2. Look into the ‘system frameworks’ for versions

The path /System/Library/Frameworks/… was where I went to look what else is inside:

$ ll /System/Library/Frameworks/JavaScriptCore.framework/Versions
total 0
drwxr-xr-x  4 root  wheel  128 Jan  1  2020 .
drwxr-xr-x  4 root  wheel  128 Jan  1  2020 ..
drwxr-xr-x  5 root  wheel  160 Jan  1  2020 A
lrwxr-xr-x  1 root  wheel    1 Jan  1  2020 Current -> A

Aha, there’s a link named Current that (currently) points to A. I used this link in the next step. This way I can still use the same link, even if (when!) an OS update causes the file that’s linked to changes.

3. Link to the current version

I set a link somewhere in within $PATH. I have a bin folder in my home directory, so it put the link there:

ln -s /System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Helpers/jsc ~/bin/jsc

3. Set a variable ‘console’ for output

To output things, use this to define a variable console in a running JavaScript shell.

var console = {log : debug};

While jsc provides a print function, I find it convenient to stick to the more idiomatic console.log.

4. Use ‘jsc’

$ jsc
>>> var console = {log : debug};
undefined
>>> console.log(function(){})
--> function (){}
undefined
>>> 1 + 1
2