Search code examples
javascriptlogical-or

what does this (h.hj=h.hj||function(){.....) syntax do?


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.


Solution

  • 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) };

    It's a Javascript expression. It assigns a function to an hj property on an object named h.

    Wanted to understand what purpose does h.hj = h.hj serve before the OR condition.

    h.hj = h.hj is regular assignment. If h.hj is truthy then h.hj is reassigned back to itself.

    Want to understand the purpose of the syntax and why its written that way.

    This overall looks to be an expression to assign a singleton function to h.hj (whatever that is) that pushes arguments into an h.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 this h.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 an arguments variable is pushed into the array.