Evaluating an expression that includes assignment?

I’m working on Node over at Codeschool*, but I ran into a line of syntax that makes my head get twisted up, and I think it’s more a simple JS question. In the code:

var file = fs.createReadStream('fruits.txt');
file.on('readable', function() {
  var chunk = null;
  while (null !== (chunk = file.read())) {
    //do something
}

I find the line with the while statement difficult to read out loud. “While null is not equal to chunk equals filewait a minute?!” I mean, I see the point–chunk starts off null, and as you .read() the file, one chunk at a time, if that chunk !== null, do something. It’s the order of things that puzzles me. True or false, in that line we’re first reassigning chunk (previously null) to the output of file.read(), and then asking whether it’s still null or not? How come it can work sorta right-to-left like that? Is this some kind of order-of-operations thing, stuff in parentheses gets done first before being evaluated?

* And yes, a few steps later they have you replace this code with .pipe(); they’re just showing you what pipe does.

Okay, yeah, Googling after posting:


I guess what I said is true. I’ve always thought about Order of Operations just in terms of numerical math operations, but I guess it’s a way of forcing that assignment to be made before the evaluation.

Right – I think you’ve solved this yourself, but that code is basically the same as:

while(chunk != null)

They’ve just included the assignment to the chunk variable inside the while condition. I’m not a huge fan of the way that’s written, specifically I dislike putting null on the left hand side of the operator.