-6

I was trying to learn some JS from this HTML5 canvas snake game guide.

But I’m stuck at the part with the push:

for (var i = length; i >= 0; i--) {
  snake.push({ x: i, y: 0 });
}

Can anyone explain this to me?

Sebastian Simon
  • 14,320
  • 6
  • 42
  • 61
RKJ
  • 25
  • 3
  • 2
    Is the documentation on sites like MDN not enough? – Luca Kiebel Jun 06 '18 at 19:59
  • 1
    [Arrays - Learn web development | MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays) – Andreas Jun 06 '18 at 19:59
  • It's almost like you didn't even try to look it up: https://www.w3schools.com/jsref/jsref_push.asp – Phil N DeBlanc Jun 06 '18 at 20:00
  • Are you confused about the [object literal syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)? – Sebastian Simon Jun 06 '18 at 20:04
  • I mean the part with the variables in the paranthesis – RKJ Jun 06 '18 at 20:05
  • @RKJ Which one? `i`? `length`? `snake`? – Sebastian Simon Jun 06 '18 at 20:06
  • So there are two things. There is the object initializer (the curly braces and what is in it). This is a short way of making an object with properies `x` which set to the value of `i` and `y` set to `0`. And there is the push method which appends something to an array. That something in this case is the object mentioned before. I guess this is initializing the snake in the top left corner, where it will occupy the squares `0` to `length`, where `length` is likely the initial length of the snake. – GolezTrol Jun 06 '18 at 20:33

1 Answers1

1

push is a method which pushes the data at the end of the existing array without having to know the index of your array. so if your data is not for a specific index and can be at the end in stack, just use the push method. the output would be-

old val of array1 : ['ab','bc', 'ca']

array1.push('cz');

new value of array1 : ['ab','bc', 'ca', 'cz']

GolezTrol
  • 109,399
  • 12
  • 170
  • 196
Vaibhav
  • 83
  • 11