Wanted to understand what does this below syntax do and what is it called.
h.hj=h.hj||function(){ (h.hj.q=h.hj.q||[]).push(arguments) };
Wanted to understand what purpose does h.hj=h.hj serve before the OR condition.
Want to understand the purpose of the syntax and why its written that way.
2
Answers
It’s a Javascript expression. It assigns a function to an
hj
property on an object namedh
.h.hj = h.hj
is regular assignment. Ifh.hj
is truthy thenh.hj
is reassigned back to itself.This overall looks to be an expression to assign a singleton function to
h.hj
(whatever that is) that pushesarguments
into anh.hj.q
array each time it’s called.The first time this is called
h.hj
is likely undefined, so the function callback is assigned. On subsequent calls since thish.hj
function is defined, i.e. truthy, it’s simply reassigned back to itself.In the callback an
h.hj.q
array is created if it does not exist, and on each function call anarguments
variable is pushed into the array.I’ll break it down for you…
h
should be defined before this expression. It should be a function or an object.h.hj = h.hj || function(){ ... }
retainsh.hj
value if defined or, if undefined/falsy, defines it asfunction(){ ... }
.Inside the function,
h.hj
should be the function itself (if not defined anywhere else).h.hj.q
retainsh.hj.q
value if defined or, if undefined/falsy, defines it as[]
.Then the function just push the arguments given to the function into the
h.hj.q
which should be an array.The main behavior here is that the function attaches every parameter given in its calls to the
q
property of the function itself. Then, later you can recover all those parameters through the function object itself.