Clojure examples compared to JavaScript counterparts.
Defining vars:
Creating maps:
Maps are functions:
Functions are values:
Defining and using functions:
Defining and using anonymous functions:
((fn [x] (* x x)) 3)
;; ⇒ 9
;; % represents the first argument to the anonymous function.
;; We could have also used %1 to get at the first argument.
;; This function is the same as function above.
(#(* % %) 3)
;; ⇒ 9
Clojure sequences are lazy:
;; Take the first ten even numbers from a list of size one billion.
;; List is lazily built, so it never builds all billion elements.
(take 10 (filter even? (range 1000000000)))
;; ⇒ (0 2 4 6 8 10 12 14 16 18)
The JavaScript counterpart may crash your browser:
// With Underscore.js
_.chain(_.range(1000000000))
.filter(function (n) { return n % 2 == 0; })
.take(10)
.value();
// ⇒ ?
Defining and using functions, with a destructured map in function argument:
(defn my-function
[{:keys [name occupation]}]
(println name "is a" occupation))
(my-function {:name "Elben"
:phone "5555555"
:occupation "Farmer"})
;; ⇒ Elben is a Farmer
JavaScript doesn’t support destructuring:
var myFunction = function(map) {
console.log(map.name + " is a " + map.occupation);
};
myFunction({name: "Elben",
phone: "5555555",
occupation: "Farmer"});
// ⇒ Elben is a Farmer
If you’re interested in learning more, I recommend Joy of Clojure.