2.1 Javascript Functions… the right way

Last week, I made a huge *mistake* in one of the tutorials, instructing the creation of a function within a function.  While this method works in this particular example, it is a poor decision for various reasons.  Why?  When you put a function within a function, then that function only exists (and is therefore usable) within that function.  If you want a function to work globally, then it needs to be put on its own, and not within any other function.

Let’s take a look at the code from last week’s function tutorial:

Here, you will notice that the function “createMarker” is inside of the function “initialize”. This means that createMarker can only be called from inside of the initialize squiggly brackets. In order to allow you to use the function outside of the “initialize”, let’s move the createMarker code:

 

This is better. But there is still one more task to do. The variable for “map” is defined inside of the “initialize” function. Again… this means that the variable can only live inside of the “initialize”. If you then look at the createMarker function, you will notice that the variable “map” is being called. This will make that function not recognize the “map” variable, and therefore the code will not complete. To fix this problem, let’s move the creation of the “map” variable outside of the “initialize” function. Also, make sure to get rid of the “var” part before the map variable inside of the initialize function, because you don’t want to declare a variable twice (line 23 below).

 

Leave a Reply