Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a parenthesized expression in Javascript return a reference?

Tags:

javascript

I understand that a parenthesized expression in Javascript returns the result of evaluating the expression in parentheses:

x = ( 1, 2, 3 );

will evaluate the three expressions above, and return the result of the last one: '3', as mentioned in some other posts.

The following example code from SlickGrid contains something I'm not quite sure I understand:

  $(function () {
    for (var i = 0; i < 500; i++) {
      var d = (data[i] = {});
      d["title"] = "Record " + i;
      d["n1"] = Math.round(Math.random() * 10);
      d["n2"] = Math.round(Math.random() * 10);
      d["n3"] = Math.round(Math.random() * 10);
      d["n4"] = Math.round(Math.random() * 10);
      d["n5"] = Math.round(Math.random() * 10);
    }
    grid = new Slick.Grid("#myGrid", data, columns, options);
  })

In particular the expression:

var d = (data[i] = {});

appears to return a reference to the associative array initialized in the parenthesized expression.

Is that indeed what is going on? Is there a more detailed explanation of this? Is there a reason to do this instead of something more obvious, like creating the associative array 'd', and then setting it to 'data[i]'?

like image 691
si28719e Avatar asked Feb 16 '23 15:02

si28719e


2 Answers

Yes. With the line:

var d = (data[i] = {});

The variable d and data[i] will both end up referring to the same empty object created by {}.

In JavaScript the = operator both sets the variable on the left and returns the value being set. This means you can do an assignment in the middle of another expression, possibly with parentheses to ensure correct order of operation.

In your example the parentheses are optional - the following would have the same result because the associativity of = is right to left:

var d = data[i] = {};

Another arbitrary example is doing an assignment in a function call's argument:

alert(d = "hello");

Or when assigning an object reference you can use the result to operate on the object involved:

var d;
(d = {}).prop1 = "test";
console.log(d.prop1);   // prints "test"
like image 125
nnnnnn Avatar answered Feb 18 '23 10:02

nnnnnn


It's just a short hand.
Your code

var d = (data[i] = {})

Is equal to

 data[i] = {};
 var d = data[i];
like image 41
jantimon Avatar answered Feb 18 '23 09:02

jantimon