Clojure examples compared to JavaScript counterparts.
Defining vars:
(def age 100)// JavaScript
var age = 100;Creating maps:
{:foo 0 :bar {:car "far"}}// JavaScript
{foo: 0, bar: {car: "far"}}Maps are functions:
({:foo 0 :bar {:car "far"}} :foo)
;; ⇒ 0// JavaScript
var o = {foo: 0, bar: {car: "far"}};
o.foo
// ⇒ 0Functions are values:
(map inc [1 2 3])
;; ⇒ [2 3 4]// With Underscore.js
_.map([1, 2, 3], function (n) { return n + 1; });
// ⇒ [2 3 4]Defining and using functions:
(defn square [x] (* x x))
(square 3)
;; ⇒ 9// JavaScript
function square(x) { return x * x; }
square(3);
// ⇒ 9Defining 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// JavaScript
(function (x) { return x * x; })(3);
// ⇒ 9Clojure 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 FarmerJavaScript 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 FarmerIf you’re interested in learning more, I recommend Joy of Clojure.