The following code is used in service.js to create an instance of a 2D map:

map = new google.maps.Map($("#map").get(0), { // object containing map options here})

I learned from the jQuery api that the .get(0) method will select the very first html element having id #map. When you have a look into index.html file, you will note that there is only one element with an id of #map. Given there is only one element with the id #map, what purpose does the method .get(0) serve?


It sounds like what you mean to ask is, "Why not use .get() without any arguments, since there's only one element to choose from?" Well, you could do that, but there are a few good reasons to use .get(0) instead.

First, .get() returns an array, so you still have to pick the first element out even if there aren't any other elements. That 0 is going to pop up sooner or later; there's no avoiding it.

Second, service.js doesn't actually know what's in index.html. All service.js knows is that, to do its job, it needs a single #map element with map options. Maybe there are additional #map elements in the page that are intended to do something else; service.js doesn't care and doesn't want to potentially grab a bunch of useless junk along with the one element it needs. Using .get(0) communicates right away that this script only wants one element, and it needs to come first. It's clear and explicit, which are good qualities for code to have.

Third, consider flexibility. If there are no #map elements, then the page will break; from the perspective of service.js, that's the fault of whoever wrote index.html. If you choose to use service.js on your page, you're responsible for supplying it with what it needs. Now, if you have some extra #map elements that you want to use for your own purposes, why should service.js care? This isn't a case like ealier problem sets in C where we had to control the number of arguments that the user gave at the command line, and complain when we got too much information. That was a complete, isolated program; service.js is just one component of many, and it shouldn't impose unnecessary restrictions on the other components. Using .get(0) is a good way to make sure that any extra elements on the page won't impact our component.

In a professional environment, most production code has had more than one programmer working on it at one time or another. The more complex an application becomes, the more likely it is that different components are written by different people. As a result, it's incredibly useful to get in the habit of writing each component in a way that interfaces clearly and efficiently with other components. If you know you want just one element, and you have a choice between a method that returns an array of all elements or an overloaded method that returns just one element, you should prefer the method that returns just one element.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .