3

How do I write the following in clojurescript?

obj = {"a" : 4};
"a" in obj;
bluegray
  • 600
  • 8
  • 18

2 Answers2

11

exists? was added to check for undefined in ClojureScript :

   (ns my.ns
     (:require-macros [cljs.core :refer [exists?]]))

   (if (exists? js/jQuery)
      (println "jQuery"))
      (println "no jQuery"))

One can also use aget and nil? to avoid calling JavaScript functions :

(def scope (js-obj))
(aset scope "var1" "Value")
(aget scope "var1")               ;; "Value"
(aget scope "anotherVar")         ;; nil
(nil? (aget scope "anotherVar"))  ;; true
nha
  • 17,623
  • 13
  • 87
  • 133
7

Following the accepted SO way to check if a js object property exists using the method "hasOwnProperty" We can translate it as follows:

(def foo (js-obj "bar" "baz"))
(.hasOwnProperty foo "bar")
;; => true
(.-bar foo)
;;=> "baz"
(.hasOwnProperty foo "car")
=> false
(.-car foo)
;;=> nil
Community
  • 1
  • 1
tangrammer
  • 3,041
  • 17
  • 24