loading...
Cover image for Declaring Javascript Functions

Declaring Javascript Functions

raddevon profile image Devon Campbell Originally published at raddevon.com on ・8 min read

In the previous article in this series on Javascript functions, I talked about how a function in Javascript is like a play in football. In this article, I’ll show you how to declare one in your app so you can start using it in your code.

Like Writing Out Your Play

Declaring a function is like writing out your play in the playbook. Once you’ve declared it, you can “call” it by name, and your app will know exactly what to do. Here are the parts of a basic function declaration.

Diagram of a Javascript function declaration highlighting the function keyword, the name of the function, the function parameters, and the functions code.

Parts of a Function Declaration

Let’s look at the parts of this simple function that makes your text more exciting by returning it with an exclamation point.

Function Keyword

The function keyword tells Javascript that what follows is a declaration of a function.

Name

The name of the function is what you will use to call it later. It should be distinct from any of the other functions and variables in the same scope. (More on scope in a later article.) The name can’t be exactly the same as any of the Javascript keywords.

In this example, you’d call the function with the name addExcitement.

Parameters

Parameters allow you to add new information when you call your function to affect the outcome. The parameters are listed inside parentheses right after the name of the function. In this example function, you’re providing the text you want to make exciting and the function will add an exclamation point to the end and return it.

The data you provide when calling the function is called an argument. That means, you have two names for the same data: parameter and argument.

Back to our sports analogies: think of a pass in football. A “pass” is a “pass” if you threw it, but it’s a “catch” if you caught it. Two names for the same thing, just like the parameter/argument. The argument is like the pass because you are passing the data in, and the parameter is like the catch because the function is taking that data and using it. Function declarations have parameters and function calls have arguments.

The name text I chose for the parameter is not magical. The name could have been anything like dog or love. Those wouldn’t have been very good, though, because it would have made the function more difficult to understand when you read it.

You’ll notice the name of the parameter gets repeated in the actual code on the return line. Whenever you use a parameter’s name inside your function, that name will get replace by the argument data when the function is called. If I called this function and passed in a string 'Hey' as the argument for the parameter, the spot where I used text on the return line would be replaced by that string 'Hey'. If the code contained other instances of text, those would also get replaced by "Hey". (To be clear, the code doesn’t actually change, but as the function runs, Javascript looks at the parameter as if it were instead the data passed as the argument. Kinda the same way a variable gets seen as its value when Javascript is running.)

This function has a single parameter, but a function could have two or three or as many as you want. To have multiple parameters, you just add new parameter names inside the parentheses, putting a comma between each one. You can use each one inside your function code and each will get “replaced” by its corresponding argument when the function is called.

The corresponding argument is the one in the same position as the parameter. If I had this function that just logged out three parameters:

function logAll(param1, param2, param3) {
  console.log(param1);
  console.log(param2);
  console.log(param3);
}

and I called it like this: logAll('everybody', 'dance', 'now')

the function would log the arguments out in the same order I passed them since 'everybody' corresponds to param1 because they are both in the first position, 'dance' corresponds to param2, and 'now' corresponds to param3. The arguments are matched up with the parameters in the same position and then the function runs replacing the parameters with the matching arguments.

If I changed the function to this:

function logAll(param1, param2, param3) {
  console.log(param2);
  console.log(param3);
  console.log(param1);
}

and called it the same way as before, the function would now log 'dance' first since it is the argument corresponding to param2 which is the first parameter to get logged. It would then log 'now' which corresponds to param3 followed by 'everybody' which corresponds to param1.

Code

After you close the parentheses on your parameters, you’ll open a set of curly braces which will contain your function’s code. Any code you can write outside a function, you can write inside a function. Whatever code you write inside the curly braces will be executed each time the function is called.

Functions can be a single line of code, 1,000 lines, or anything between. In general, you’d like each of your functions to do one job. This will make your code easier to read and your app or web site easier to debug. That means, most functions will be on the shorter side.

Your function code has access to a special keyword that doesn’t work outside the body of a function: return. When a function returns a value, your call to that function will get replaced by your value when the code runs. If we look at the addExcitement example from earlier, you’ll see a function that returns a value.

If we called that addExcitement function without doing anything else, the resulting exciting text would just sort of evaporate into the ether. If we want to do something with the resulting exciting text, we might capture it into a variable like this:

const excitingText = addExcitement('Hey');

That will leave me with a variable called excitingText which contains the value returned by the function — in this case, 'Hey!'.

If I don’t need to use the value returned by the function later, but I do need to log it now, I could do that instead.

console.log(addExcitement('Hey');

This code will log out the value returned by our function which would be “Hey!”

Simply calling the function like this:

addExcitement('Hey');

will return the value, but since it’s not getting logged, captured in a variable, or added to the DOM, you’ll never actually see the result of it.

Functions can return values directly or they can return anything that resolves to a value (called expressions). That means you could return 13 or 12 + 1 or a variable or a condition like text.length > 1.

Although functions can return values, they don’t have to. The other example I’ve used in the article — the logAll function — does not return a value. Instead, it has a side effect. By calling console.log, the function causes data to be logged out to the Javascript console.

Be careful about the timing of returning values. Once you return a value from the function, that ends the function. Code beyond your return is never executed.

Sometimes, you might have a conditional return inside an if statement. In that case, you might still have code after the return that gets executed if the condition isn’t met, but be aware that a return is a hard-stop for your function.

Other Ways to Declare

Now that you know the parts of a function declaration, we can look at a few other ways to declare a function.

Function Expression

The function expression method of declaring a function looks very similar to the function declaration except that you are assigning your declaration to a variable.

const addExcitement = function(text) {
  return `${text}!`;
}

The main difference in this way of declaring a function is that, with the function declaration, the function is hoisted. This means the function is actually defined at the top of your Javascript instead of where it actually appears in the code.

If I try to call my function above the point in my code where it is defined, it will work as expected if I declared using a function declaration. If I declare using a function expression, it will throw an exception because the function is not yet in our application.

Arrow Function

An arrow function is a newer type of function expression with a more compact syntax. It looks like this when declaring a function with a single line of code that is returned:

const addExcitement = (text) => `${text}!`;

As you can see, it’s really compact compared to the other methods of declaring a function. They are called arrow functions because of the fat arrow (=>) used in the expression. For arrow functions with a single parameter like this one, you can make them even a little more compact by omitting the parentheses around the parameter name. If you have multiple parameters, the parentheses are required.

In a one-liner arrow function like this, the expression after the arrow is automatically returned without the need for the return keyword.

Arrow functions can also be multiple lines if you add curly braces.

const logAll = (param1, param2, param3) => {
  console.log(param1);
  console.log(param2);
  console.log(param3);
}

Like the other function syntaxes, a multi-line arrow function does not return a value unless it’s preceded with the return keyword.

The value this inside an arrow function may be different from a function declared some other way. this is a value in Javascript that changes based on the context that references it. By default, it refers to the object containing the reference to this. Since a function is an object, this inside a function usually references that function by default, which isn’t all that helpful.

It’s common to write a function as an object property. You might want to use this inside that function (now called a method since it lives on an object) to refer to the object instead of to the function itself. Here’s an example.

const devon = {
  email: 'devon@raddevon.com',
  sendEmail: function(emailBody) {
    email.send(this.email, emailBody)
  }
}

The object devon has two properties: email which contains my email address as a string, and a method sendEmail that uses that fictional email object’s send method to send me an email by referencing the object’s own email property using this.email.

We’re pretending, for the purposes of this example, that we have an email object accessible to this object which has a send method that will send an email given two arguments: the address and the body of the email to send.

The problem here is that, even if we had our mythical email object, the code wouldn’t work. That’s because this inside the sendEmail method references the sendEmail method itself, which has no email property.

If we write the method as an arrow function instead, though, it binds the current value of this in the context in which the function is declared to the value of this inside the function. In other words, whatever is this where we declared the function will also become this inside the function.

If you want to write a function that doesn’t reference this as an arrow function, go for it. This attribute of arrow functions won’t affect you at all in that case.

Arrow functions are handy in a lot of situations. One of the most common one is callback functions. If you want to learn about those, head to Rad Devon where you can get a chance at a free mentoring session and get notified about new articles as they're released.

Articles in This Series

  1. Your App’s Playbook: Why Use Functions in Javascript
  2. Declaring Javascript Functions
  3. Understanding Javascript Callback Functions
  4. Marie Kondo Your Javascript Code with Functions

Posted on by:

raddevon profile

Devon Campbell

@raddevon

I help people leave their 💩 jobs to become web developers.

Discussion

markdown guide