What is the interpretation of this line in Javascript.
var x[],matrix[],n;
...
n = (matrix = x) && matrix.length;
Despite I searched for it, I couldn't find any tips.
Thank you
It does this:
x
to matrix
; the result of the matrix = x
expression is the value that was assigned (this is true of all assignment expressions). Let's call that value "x-value". I don't want to call it x
from here on out, because x
is only evaluated once.matrix.length
to n
; otherwise, assigns x-value to n
.So for instance, if x
is []
, the code sets matrix
to point to the same empty array x
does and sets n
to 0
(matrix.length
after the assignment). Other examples (I'd written these before you edited your question): If x
is "foo"
, it sets matrix
to "foo"
and sets n
to 3
(the length
of matrix
). If x
is ""
(a falsy value), it sets matrix
to ""
and sets n
to ""
. If x
is {foo:"bar"}
, it sets matrix
to refer to that same object and sets n
to undefined
(since the object has no length
property). You get the idea.
#2 above comes about because &&
is not just a simple logical AND operator. a && b
works like this:
a
to get its value; let's call that a-value&&
operator is a-valueb
and make that the result of the &&
operator1 "Truthy" values are any values that aren't "falsy." The falsy values are 0
, null
, undefined
, ""
, NaN
, and of course, false
.
We can interpret it as some pseudocode like this:
var x[],matrix[],n;
...
matrix = x
if(x is not in [null, false, 0, undefined, "NaN",""])
n = matrix.length
else
n = x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With