Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The interpretation of one line Javascript code

Tags:

javascript

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

like image 218
Saman Avatar asked Dec 18 '22 14:12

Saman


2 Answers

It does this:

  1. Assigns the value of 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.
  2. If x-value is truthy1 (coerces to true), it assigns 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:

  1. Evaluate a to get its value; let's call that a-value
  2. If a-value is falsy, the result of the && operator is a-value
  3. Otherwise, evaluate b and make that the result of the && operator

1 "Truthy" values are any values that aren't "falsy." The falsy values are 0, null, undefined, "", NaN, and of course, false.

like image 54
T.J. Crowder Avatar answered Jan 03 '23 11:01

T.J. Crowder


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
like image 25
jinus b Avatar answered Jan 03 '23 11:01

jinus b