Search code examples
javascriptobjectobject-literal

Is there a simple way to make these two lines into a one-liner?


Here are the two lines:

pixels[x-left] = {};
pixels[x-left][y] = true;

It would greatly allow me to clean up some code if the two could be combined into a single expression.

My first attempt looked something like this:

pixels[x-left] = { y: true };

However the letter y is being used as the index instead of the value of y, which is not OK.


Solution

  • I'll start right off saying that Bergi's solution should be preferred, but in case you don't mind killing your code's readability:

    (pixels[x-left] = {})[y] = true;
    

    Fiddle

    This works as an assignment expression returns the assigned value (in this case, a reference to the assigned object).