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 && "*"
Now I am still quite new to Javascript and these shortened uncommon javascript codes are still very foreign to me, this is the first time I have come across them.
Does anybody know what this does? I attempted it in a javascript code tester ad it just returned *, so I do not know.
Also, if anybody knows where I can look to find out what these uncommon lines of code do, that would be very helpful. They are all shortened and are sorts of things like this and
a = a || b
(I know what that one does)
But If there is some sort of name for this kind of javascript or a reference I can look at, that would be very helpful, I have been scouring Google for hours.
Thanks
If
ais truthy, it assigns"*"toa.If
ais falsy, it remains untouched.&&has short-circuit semantics: A compound expression(e1) && (e2)—wheree1ande2are arbitrary expressions themselves—evaluates to eithere1ife1evaluates to false in a boolean context—e2is not evaluatede2ife1evaluates to true in a boolean contextThis does not imply that
e1ore2and the entire expression(e1) && (e2)need evaluate to true or false!In a boolean context, the following values evaluate to
falseas per the spec: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 toaifais falsy, which is then in turn assigned toa, i.e. the statement simplifies toa = a.If
ais truthy, however, the expression on the right-hand side evaluates to*, which is in turn assigned toa.As for your second question:
(e1) || (e2)has similar semantics:The entire expression evaluates to:
e1ife1is truthye2ife1is falsy1 Exception