Reputation: 710
I have two code snippets that I assumed to both result in alerts. However the first results none while the second performs the alerts.
(map #(.alert js/window %) ["hey1" "hey2"])
This slight modification prints (nil nil) as expected, as well as fixing the alert issue. The question being WHY?
(print (map #(.alert js/window %) ["hey1" "hey2"]))
Another weird observation is that the first snippet works from a browser-repl, but not when typed into code.
Is the map function side effect free, but print is not? Maybe some core code optimization I do not know about?
Work-arounds and answers are both appreciated. If you need more info please let me know in a comment.
[org.clojure/clojurescript "1.8.51"]
BOOT_CLOJURE_VERSION=1.7.0
BOOT_VERSION=2.5.5
java version "1.8.0_101"
Description: Ubuntu 14.04.4 LTS
Upvotes: 1
Views: 86
Reputation: 47012
You don't want to use map
for a side-effecty operation like alert. The issue you are seeing is a result of map
being lazy, so it won't actually do the work until you consume the elements of the resulting sequence. If you really want to do side-effect sort of things, doseq
might be a better option, especially if you don't need a sequence of results:
(doseq [msg ["hey1" "hey2"]]
(.alert js/window msg))
Or you can use doall
to force the evaluation of the whole sequence:
(doall (map #(.alert js/window %) ["hey1" "hey2"]))
Upvotes: 5