How do I write the following in clojurescript?
obj = {"a" : 4};
"a" in obj;
How do I write the following in clojurescript?
obj = {"a" : 4};
"a" in obj;
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
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