1
votes

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

1
Possible duplicate of Side effect optimized out - Nathan Davis
Yes they are both talking about the same topic. However the type of people who are wondering this question likely do not know what a side effect is or that it is what is causing their problem. Thus I think my question is more likely to be found by the people who need its answer. In summary the only reason for keeping this question here is that it does not contain the words side effect in the question If you don't think this is important, then it would be reasonable to remove it. - Jason Basanese

1 Answers

5
votes

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"]))