1

What order does the following statement run? Does the runtime execute it from right to left?

  length = i = test = output = null;
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
wayofthefuture
  • 8,339
  • 7
  • 36
  • 53
  • How would you test in what order this executes? (Or is that a really stupid question; sorry, it's been a very long day (and night)...) – David Thomas Aug 28 '13 at 18:52
  • There isn't really a way to "test" the order in which they execute. You could open a javascript console (probably by hitting Ctrl/Cmd + Shift + I in your browser right now) and paste in the above code. Then when you tested the values of each variable, you would find them all to be null. Interestingly, since there is only one operator ("="), and since it works from right to left, the only way that this could work would be from right to left, otherwise, everything would have a value of length, including null... wait, what? – John Henry Aug 28 '13 at 19:01
  • That was my assumption, but I assumed I must be missing something (perhaps) obvious... – David Thomas Aug 28 '13 at 20:11

4 Answers4

6

Yes, since an assignment expression is not a lefthand-side expression itself, the nesting is

(length = (i = (test = (output = null))));

It is executed from outside-in, solving references left-to-right (first getting the length variable, then evaluating the right side, which is getting the i variable and evaluating …). That means output is the first variable that is getting assigned to, then test, then i, and last length: "right-to-left" if you want. Since the assignment operator always yields its right operand, everything will be assigned the same (innermost, rightmost) value: null.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
3

Does the runtime execute it from right to left?

Yes.

foo = {
    set a() {
        console.log('a');
    },
    set b() {
        console.log('b');
    },
    set c() {
        console.log('c');
    },
    set d() {
        console.log('d');
    }
};
foo.a = foo.b = foo.c = foo.d = 'bar';

produces:

d
c
b
a

in the console. This order is necessary because each assignment relies on the return value of the previous assignment:

foo.a = foo.b = foo.c = foo.d = 'bar';

is equivalent to:

foo.a = (foo.b = (foo.c = (foo.d = 'bar')));

However it is not equivalent to:

foo.d = 'bar';
foo.c = foo.d;
foo.b = foo.c;
foo.a = foo.b;

The return value of a = b is b. This is especially important to remember should you choose to implement accessors and mutators.

What this means is that my previous example is equivalent to:

foo.d = 'bar';
foo.c = 'bar';
foo.b = 'bar';
foo.a = 'bar';
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
2

Yes, it executes from right to left. The value of everything is now null.

John Henry
  • 2,419
  • 2
  • 20
  • 22
1

That single line assignment is equivalent to this

output = null;
test = output;
i = test;
length = i;
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155