Harry B. Harry B. - 1 month ago 8
Javascript Question

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];
},

Answer

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)
}
Comments