What does var = var && “*” mean in Javascript

后端 未结 1 1574
孤独总比滥情好
孤独总比滥情好 2021-01-06 01:22

I am trying to work out some obfusicated code by reading it, and I was doing pretty well until a came across this:

a = a && \"*\"

N

相关标签:
1条回答
  • 2021-01-06 02:06

    If a is truthy, it assigns "*" to a.

    If a is falsy, it remains untouched.


    && has short-circuit semantics: A compound expression (e1) && (e2)—where e1 and e2 are arbitrary expressions themselves—evaluates to either

    • e1 if e1 evaluates to false in a boolean context—e2 is not evaluated
    • e2 if e1 evaluates to true in a boolean context

    This does not imply that e1 or e2 and the entire expression (e1) && (e2) need evaluate to true or false!

    In a boolean context, the following values evaluate to false as per the spec:

    • null
    • undefined
    • ±0
    • NaN
    • false
    • the empty string

    All1 other values are considered true.

    The above values are succinctly called "falsy" and the others "truthy".

    Applied to your example: a = a && "*"

    According to the aforementioned rules of short-circuit evaluation for &&, the expression evaluates to a if a is falsy, which is then in turn assigned to a, i.e. the statement simplifies to a = a.

    If a is truthy, however, the expression on the right-hand side evaluates to *, which is in turn assigned to a.


    As for your second question: (e1) || (e2) has similar semantics:

    The entire expression evaluates to:

    • e1 if e1 is truthy
    • e2 if e1 is falsy

    1 Exception

    0 讨论(0)
提交回复
热议问题