To add to data2704285749’s beautiful explanation:
- Under the hood,
forEach
looks like this:
Array.prototype.forEach = function (callback) {
if (callback && typeof callback === 'function') {
for (var i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
}
};
So, any array has a method forEach
which accepts function as a parameter and calls it inside of forEach
.
If you haven’t yet study prototypes - don’t go deep into Array.prototye
. This is another big topic (but stydy prototypes in the future - you should at least understand the concept of it to know how JS works).
It basically means that whatever we put in the array’s prototype, it will be accessed by any array in the future. In our case forEach
exists there by default.
this
keyword in this very case refers to a particular array we call the method on.
Fist it checks that we indeed passed a function, not some other type - if (callback && typeof callback === 'function')
Then it iterates over the array and calls the function on each item.
Every time it passes it the current item’s value - this[i]
, current item’s index - i
, and the array itself - this
.
You can do whatever you want with them in your callback function you pass to forEach
.
- If I understand the code correctly,
checkCollisionBottom
checks whether the object passed as first argument collides with the object passed as a second argument from the 1st object’s bottom.
To check this you should pass two objects to it in a specific order for the checks inside of checkCollisionBottom
to work properly. The order affects the result of the comparison as you can see form the function’s body.
Both argument objects should have at least x
and y
fields, which, I assume, refer to their origin points coordinates. They have origins in the upper left corner and 1st object has a height of 20, 2nd object has a width of 58, and this is hardcoded in checkCollisionBottom
checking expression, if I understand it correctly.
-
item
and index
are totally arbitrary argument names. Order and value type of both of them is what important here. These names and their values will be accessible within you callback function only.
So having in mind what I told in 1., index
- as it is called here - contains current item’s index and is passed to slice
method as a first argument.
It will work too if you rewrite the code so that you have a for
loop. I assume that this code’s logic requires each item’s index and if you don’t know the array’s length (which you shouldn’t) - you have to iterate over array any way you want and get each item’s index, passing it to splice
method.