Search code examples
debuggingclojurescript

js/console.log in ClojureScript


I want to implement a function with ClojureScript to simplify js/console.log like this:

  (defn log [& args]
      (apply js/console.log args))

Calling it : (log "foo" "bar") throws: TypeError: Illegal invocation

but this works : (js/console.log "foo" "bar")

What is the problem ?


Solution

  • js/something is for accessing a js object, but you shouldnt nest dots after that, since it is not clojure compatible syntax and it was going to be removed. In older versions of the compiler (2138) your code works, but it is possible that it has been deprecated in newer versions of the compiler. Which version are you using?

    The correct way would be using straightforward js interop like this: [Caveat: see comment below from David Nolen, ClojureScript lead developer]

    (defn log [& args] (apply (.-log js/console) args))
    

    And even shorter, since console.log is already variadic (just make an alias):

    (def log (.-log js/console))