Harry B.
Harry B.

Reputation: 421

What does this JavaScript syntax mean in regards to .unshift()?

I saw this code on a tutorial and I don't know what is going on in the unshift method. I understand what .unshift() does in js, but I don't understand what this syntax is doing, specifically the fact that it is written as x:x and y:y.

insert: function(x, y) {
        this._queue.unshift({x:x, y:y}); // unshift prepends an element to array
        this.last = this._queue[0];
    },

Upvotes: 0

Views: 131

Answers (3)

Nick Zuber
Nick Zuber

Reputation: 5637

Unshifting an element to an array simply inserts that element into the front of the array.

Here, we have some array called _queue in which we are inserting {x:x, y:y} to the front.

So if the queue looked something like this:

_queue: [
  {x:1, y:1},
  {x:2, y:2},
  {x:3, y:3},
  ...
];

it now would look something like this:

_queue: [
  {x:x, y:y}, // what you had just inserted
  {x:1, y:1},
  {x:2, y:2},
  {x:3, y:3},
  ...
];

The insert function where this is being called takes two parameters of x and y, so when we insert an object like:

{x:x, y:y}

What this really means is that we're inserting an object who's fields are:

{
  x: x, //(whatever argument was passed in for `x` when the function was called)
  y: y  //(whatever argument was passed in for `y` when the function was called)
}

Upvotes: 2

Keith Nicholas
Keith Nicholas

Reputation: 44306

{x:x,y:y}

is odd syntax when you first come across it, but in javascript, the key can't be a variable so is treated as a literal, and the value is the variable.

so if x =1;

var o = {
  x:x
}

will mean o = {x:1}

if you did want the key by variable then you'd use something like

var x = 1;
var key = "x";
o = {}
o[key] = x;

Upvotes: 1

Rose Robertson
Rose Robertson

Reputation: 1256

It's adding an object to the array, so if the array was previously empty, it will now look like this:

[
  {
    x: "whatever the value of x was passed into that method", 
    y: "whatever the value of y was passed into that method"
  }
]

As to why? I have no idea without seeing the entirety of the code

Upvotes: 1

Related Questions