In ClojureScript it is possible to store the original item to be destructured in a separate value. For example when calling the anonymous function below with the map {:a "A" :b "B" :c 3 :d 4}
the keys a
and b
are destructured and the original map is stored in m
using the :as
operator.
((fn [{:keys [a b] :as m}]
(println "a is" a)
(println "b is" b)
(println "m is" m))
{:a "A" :b "B" :c 3 :d 4})
;; => a is A
;; b is B
;; m is {:a "A" :b "B" :c 3 :d 4}
;; nil
Is a similar operation available in ECMAScript? E.g.,
(({ a, b }) => {
console.log(`a = ${a}`);
console.log(`b = ${b}`);
console.log(`m = ${???}`);
})({ a: "A", b: "B", c: 3, d: 4 });
Or is it necessary to store the original item first in a variable and destructure later?
((m) => {
const { a, b } = m;
console.log(`a is ${a}`);
console.log(`b is ${b}`);
console.log(`m is ${m}`);
})({ a: "A", b: "B", c: 3, d: 4 });
;; => a is A
;; b is B
;; m is [Object object]
If original parameter is supposed to be accessed, it should be destructured to variables in function body:
(m) => {
const { a, b } = m;
...
}
Even if it's not accessed, this style is beneficial because it allows to debug parameters in case of a problem, especially in native arrow functions where arguments
is not available.