BTG Coding School

Functions in Javascript

Last time we looked at variables, which just hold values for us to reuse.

In addition to storing and reusing simple data types like we saw earlier, we can actually name and reuse code as well.

Note that many programming tutorials do not teach about functions until much later. I believe it is valuable to learn how to use these early, since they offer to help organize your code. Using functions early can help develop good habits.

Calling Functions

A function is a block of code that:

  1. Takes some number(possibly zero) of inputs
  2. Does or computes something
  3. (Optional) Gives us back a value

When we use a function, we can say we are “calling” that function.

We actually called functions already in our first few lessons. Some functions we’ve seen earlier include:

function name inputs returned value example
console.log message to display None
console.log('hi');
prompt prompt message user input
prompt('Enter your name');
alert message None
alert('this is a popup');
Math.pow base, and exponent base raised to the exponent power
Math.pow(5, 2);

When we use a function, we write its name, followed by parenthesis. Inside the parenthesis we put the values for the inputs.

Creating functions

When we want to make our own function, we use the special keyword function. Let me provide an example that we can then talk through.

// This function asks the user for their name,
// then says hello.
function greeter() {
  console.log('function running!');
  let name = prompt("what is your name?");
  alert("Hello there " + name);
  console.log('function ending!');
}

// Now we can call it:
console.log('just before calling');
greeter();
console.log('just after calling');

This is the simplest form of function. It takes no inputs, returns no value, and simply does something. This function lets us build a reusable piece to perform the greeting we did in an earlier lesson. Normally, your javascript program following through your program with a finger, running one line after another. When we get to a function call, we can imagine Javascript moving its finger to the function definition, and continuing from there. When we get to the end of the function, it moves back to wherever we just called the function from.

In the example above, I added some logging lines to help explain. If you run the function (I have actually defined greeter just like above, so you can call greeter() in the console if you like.)

If we ran the example above, we would see:

just before calling
function running!
function ending!
just after calling

Notice that when we call greeter, we don’t put anything in the parentheses, since it doesn’t take any inputs.

Creating functions, advanced.

Now that we’ve looked at a basic function, lets look at a few of the other features we can use when creating functions.

// cmToMeters takes in a distance in centimeters
// and returns the value in meters.
function cmToMeters(cm) {
    console.log('function running');
    return cm / 100;
    console.log('end of function');
}

let cm = 5;
let result = cmToMeters(324);  // gives us 3.24
console.log('result: ' + result);
console.log('cm: ' + cm);
// We would see on output:
// function running
// result: 3.24
// cm: 5
// (But not end of function)

Here, we have used both the ability to take inputs, and the ability to return a value. We use inputs by giving names(variables) for each of the inputs. Here our function has only a single input, and we’ll call it cm.

When the function is called, the values we used at the place of calling are assigned to the variables for the function arguments. Since the first input provided to cmToMeters is 324, the function cmToMeters will see it as though we had just run let cm = 324; in the beginning of the function. Javascript will then run through our function code, until it reaches either the end, or the special keyword return. Return means “stop here, and give back this value.”. The function returns cm / 100, so that is the value that will get passed back to the place we called from. Result will end up storing 3.24.

Function inputs (sometimes called parameters or arguments), are scoped to the function body. Just like when we saw local variable scopes, the cm inside the function refers to the value passed in, not any possible variable also named cm before hand.

Note also that the message “end of function” is not output. When the code gets to a “return”, it will stop running the rest of the function, and jump back to the caller.

Alternative definition style

When we create functions, we’re actually just storing some code behind a variable. This can help understand the scope of function definitions as well. Some javascript projects also prefer writing functions in this way, so I’ll show you since it might otherwise surprise you later.

// This way of creating functions:
function cmToMeters(cm) {
    return cm / 100;
}

// is actually a shorthand way of writing:
var cmToMeters = function(cm) {
    return cm / 100;
};

Exercises

Here are a few practice exercises to help you learn:

  1. Create a function, isBigger(a, b), that returns true if a is bigger than b, and false otherwise.

  2. Create a function, next(num), that gives the next counting number (aka integer) right after num.

  3. (Extra challenge). Create a function, apply(f, a, b). The value f will be a function, that you should call with a and b as inputs. Then return the result.

Dont worry if this one seems tricky. I’ll explain this concept more in detail in a later lesson.

  1.  
    function isBigger(a, b) {
        return a > b;
    }
    
  2.  
    function next(n) {
        return n + 1;
    }
    
  3.  
    function apply(f, a, b) {
        return f(a, b);
    }
    

Next lesson: Conditions!

Next up, we’ll learn how to let our programs make decisions.