Saman Saman - 1 year ago 61
Javascript Question

The interpretation of one line Javascript code

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download