javascriptsafarijavascriptcore

Why doesn't console.log work in the JSC environment but it works in Safari's debug console


When I use the JSC (JavaScriptCore) engine provided in the System Library, it acts differently then when using Safari's debug console

$ /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc
>>> console.log("hello");
Exception: TypeError: undefined is not an object (evaluating 'console.log')

When console.log("hello"); works perfectly fine in Safari.


Solution

  • TL;DR

    var Console = function () {
        this.log = function(msg){ debug(msg) }; 
    };
    var console = new Console();
    console.log("hello");
    

    Safari creates a console object that is available in the debug console, but not in the JSC environment. See Safari's console documentation here

    Adding my own console object that wraps the JSC debug method solved my problem:

    $ /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc
    >>> var Console = function () {
    ...     this.log = function(msg){ debug(msg) };
    ... };
    undefined
    >>> var console = new Console();
    undefined
    >>> console.log("hello");
    -> hello
    undefined