Chapter 6 - Functions

Back to our original application (the one that was supposed to get us weather information). The next step was the following:

  1. Declare a function that is responsible for getting the weather for a given coordinate.
function getWeather(coordinate, callback) {

  var url = apiUrl +
    '?appid=' + apiKey +
    '&units=imperial' +
    '&lon=' + coordinate.longitude +
    '&lat=' + coordinate.latitude;

  makeRequest(url, callback);

}

You hear the word function and all you can think of is your math teacher in high school and it's making you sick. Well take a deep breath. Now read the first line above and relax. What do you think our function will do? It is going to get us weather information for a given coordinate, genius.

We declare a function with the keyword function and call it getWeather (see how it's using the same camelCase convention we used with variables?), and it takes arguments, in this case two arguments by the names of coordinate and callback. Boom. Those arguments are just variables that will be later passed to our function when we call it. So just like apiUrl from earlier was a variable, our arguments also carry the same properties only that they are scoped to our function and therefore they are only accessible inside of its body -- the code that is part of it and is surrounded by those curly braces.

Let's code. Type the following in your Console (use Shift + Enter to start a new line) or in an HTML file (don't forget the <script> tags if you do).

var first = 'Hello';

function scopeExample(last) {
  return first + ' ' + last;
}

console.log( scopeExample('World') ); // will print 'Hello World'

console.log(first + ' ' + last); // will error

First thing to note is the return statement in our function is used to return a value from its invocation. This may sound trivial, but in some cases you don't care for the value itself and you only care about the "side-effects" of the function. In those cases you can leave out the return statement as we've done in our weather application's functions thus far. When you leave out the return statement of a function, it will return undefined.

Second, look at how our scopeExample function takes an argument by the name of last. Later on, when we call (or invoke) the function to be executed by the computer, we pass to it the string "World" which will be mapped to the argument last.

Additionally, the above code should give you a pretty good idea as to how scopes work in JS. Our variable first was declared outside of our function's scope and therefore is considered to be in the global scope of our script. This means it can be accessed from anywhere, including from within the function as we've demonstrated above.

On the other hand, the variable last, being our function's argument, has only the scope of our function's body and therefore can only be accessed from inside our function. When we try to access the value in last outside of our function, we should get an error since it was not even declared for that external, global scope.


Functions employ the epitome of computers -- efficiency.

Why would you write this:

2 + 2 + 2 + 2 + 2 + 2;

When you can simply write this:

2 * 6;

Both of the expressions above result in the value 12 and so using the latter and shorter expression is just more efficient in terms of communicating the concept of 12 (well I guess just writing '12' would be the easiest and most efficient).

The same goes for computers: We don't want to repeat the code that's responsible for getting our weather information, so we simply put it in a function. It's an easy way to extract and encapsulate our code so we don't have to repeat ourselves when we want to execute it again.

Functions are also used to group together pieces of code that do specific things; they help us with abstraction. To illustrate the concept of abstraction, think of your phone. You most likely don't have an exact idea as to how it works, but that doesn't mean you can't use it. As a matter of fact, you're damn proficient at using it without knowing the first thing about how it works! It's the same thing with our getWeather function: Once we wrote it and we know it works (which we don't yet), all we need to remember is that it gets our weather. Once it is proven to work, how it does it is none of our concern anymore and we move on to building the rest of our application.

That's abstraction, and it is a precious concept to use when we're trying to build big and complex applications. After all, our brains are very limited. If we had to relearn each line of code to understand what our application does and build atop of it, we would quickly limit our pace of progress. Instead, I'm an advocate of grouping your code, even when used only once, into small functions with clear and descriptive names. If I see a function getWeather in any piece of software, I already have a pretty good idea as to what I can expect it to do. Don't you?

Back to our function. We called it getWeather and so we know what it does. Its execution results in our weather data. But note how getWeather itself doesn't do much. First, it constructs our URL to include the coordinates and then it just calls the makeRequest function to do the only thing it's good for -- sending a request wherever we tell it to. In this case we're going to use it to send a request to the Open Weather Map's servers for the data we need!

Table of Contents
Home