#js literal

tagged literalsince v0.0-2120Edit

Create a JavaScript object or array.

  • #js [...] - JS Array
  • #js {...} - JS Object (with stringified keys)

Details:

Data in the form of a map {} or vector [] must follow the #js tag, which will be converted at compile-time to a JavaScript object or array, respectively.

This will not implicitly convert nested data into JavaScript objects or arrays.


Examples:

#js {:foo 1 :bar 2}
;;=> #js {:foo 1, :bar 2}

#js [1 2 3]
;;=> #js [1 2 3]

For readability, it is sometimes preferable to use clj->js rather than nested #js tags.

#js {:foo #js {:bar 1}}
;;=> #js {:foo #js {:bar 1}}

(clj->js {:foo {:bar 1}})
;;=> #js {:foo #js {:bar 1}}

See Also:


Reader code @ clojurescript:src/main/clojure/cljs/tagged_literals.cljc
(defn read-js
  [form]
  (when-not (or (vector? form) (map? form))
    (throw
      #?(:clj  (RuntimeException.
                 "JavaScript literal must use map or vector notation")
         :cljs (js/Error.
                 "JavaScript literal must use map or vector notation"))))
  (when-not (or (not (map? form))
                (every? valid-js-literal-key? (keys form)))
    (throw
      #?(:clj  (RuntimeException.
                 "JavaScript literal keys must be strings or unqualified keywords")
         :cljs (js/Error.
                 "JavaScript literal keys must be strings or unqualified keywords"))))
  (JSValue. form))

Reader table @ clojurescript:src/main/clojure/cljs/tagged_literals.cljc
(def ^:dynamic *cljs-data-readers*
  (merge ;; assumes we can read all data_readers
    #?(:clj *data-readers*)
    {'queue read-queue
     'uuid  read-uuid
     'inst  read-inst
     'js    read-js}))