Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free triald h
Courses Plus Student 527 Pointsquestion about line 9 on ship_methods.js of "Writing Our First Test Suite part 1 " video
what is the purpose of the [0] on line 9 of ship_methods.js(around the 14:07 mark)?
2 Answers
nguoisechia4
Courses Plus Student 5,499 Points[0] is the index of the array of array shipPresent. First you need to understand what filter function in this example does. It will return the array of array that satisfy the condition in the function (actualCoordinate[0] === coordinate[0] && actualCoordinate[1] === coordinate[1]) . If you guess [0,0] then the condition is satisfy so shipPresent = [[0,0]] and shipPresent[0] = [0,0]. But you guess [9,9] then the condition is not satisfy then no thing is return. So shipPresent[0] = undifined.
Hans Hovanitz
923 PointsThis was confusing to me as well. How I think it is working is that it is checking if the returned filtered array has anything in it. A way to understand it that makes more sense to me is:
shipPresent = ship.locations.filter(function (actualCoordinate) {
return ((actualCoordinate[0] === coordinates[0]) && (actualCoordinate[1] === coordinates[1]));
});
if (shipPresent[0]) {
return true;
}
if (!shipPresent[0]) {
return false;
}
shipPresent is a filtered array. If there is something in the filtered array at index 0 it is true. If there is not something in the filtered array at index 0 then is is false.
When they included the [0] at the end of their return expression they were setting shipPresent to the first element in the filtered array. If there was nothing in the array it would be undefined.
Anthony c
20,907 PointsAnthony c
20,907 PointsYeah this line was kind of confusing.
Treehouse seems to make courses with "games" involving coordinates, multiple players, scores, enemies, etc. etc. I spend half the time trying to wrap my head around the mechanics of the game instead of learning the given section's/course's content. I wish they would just use a simple CRUD form for their course examples/projects as 50% of all applications are CRUD forms... sometimes the entire app revolves around CRUD.