Functions in JavaScript

An introduction to programming with functions in JavaScript

Functions in JavaScript

Photo by Patrick on Unsplash

What are Functions?

Functions in JavaScript are a fundamental building block, as is common with many other programming languages. Let’s get started with a definition and how we can declare one using JavaScript syntax.

  • A function is a block of code that performs a specific task and may also return a designated value.
  • A function can be written/programmed to do any number of things, perform specific tasks to run our code and interact with other parts of an application or program.

Functions are custom chunks of code we write to be reusable but reliable.

Common function use cases include:

  • Making calculations using the built-in JavaScript MATH functions
  • Help making API calls for data
  • Controlling program flow or execution
  • Interacting with JS Events

Functions are a powerful and fundamental tool for us as programmers to understand and feel comfortable using.

Defining a Function:

Let’s start with the basics first and build from there. We will save some more advanced features of functions (scope, hoisting, higher-order functions, callback functions, etc…) for another article.

How do we define a function?

We start by typing in the reserved keyword function followed by:

  • A name that we will use to call or invoke the function when we want to run the code.
  • Opening and closing parentheses "( )" will let us determine if the function we define will accept any outside information or parameters to use within the function body.
  • The function body consists of the list of commands or code we want to run contained within the opening and closing brackets "{ }" .
  • A return statement should be included as the last command in the function. This lets the function return data to the calling function or simply return control to the JavaScript interpreter.

Written definitions really can be confusing so let’s look at some code (or syntax).

function nameOfFunction() {
    // Code to be executed
}

Function names follow the same rules as variables do. They can contain letters, numbers, underscores and dollar signs. In JavaScript you will most often find function names using camel case. It’s also good to get into a habit of using a descriptive name for the functions that we write. This will not only help you remember what that function does with a glance at the name but can help another developer that is reading through your code to know what to expect the function logic to do.

Calling Functions:

When we want the code or logic that we defined in our function statement to run we call, or you will also hear the term invoke the desired function by name with parentheses ( ).

// Call or Invoke the function
nameOfFunction();

Ok … sure but can we see some actual code??

Let’s use the idea of a calculator and create an addition function to see some different ways we can define and use functions.

function add() {
    var num1 = 5;
    var num2 = 10;
    console.log(num1 + num2); 
}

SO, what is happening in this function and what happened to that return statement you said we HAD to HAVE at the end???

We’ll get there, like I said we are growing our understanding by starting simple and building upon what we just learned.

We started our definition with the keyword function followed by a descriptive name add( ) and our opening and closing brackets to contain our function logic. Next we define two variables num1 & num2 and assign them integer values. The last step is logging the value when variables num1 and num2 are added together.

And that return statement? The JavaScript interpreter helps us out by implicitly calling the return command for us if it doesn’t find it. Which will return control to the program once the logic in our function has completed running. We will explore what happens when we use the return statement to return a value shortly.

So, this is a very basic function and honestly not all that useful. Just adding two static values may be useful once but as developers we want to create function definitions to be as specific and reusable as possible. But this is not it, so let’s improve it by adding function parameters and return a value. Parameters are values that get passed into the function and are used as variables within the local function scope.

Scope…? So, JavaScript functions need Listerine now…?

What is scope? You might be asking. We’ll go into more depth in another article but for now let’s start with these basic guidelines. Scope determines where a variable is accessible. JavaScript has what we refer to as function scope, meaning every time a function is called, a new scope is created and any variables we define within the function body are available locally inside the function but not globally outside of it.

Note: Within the body of a function, a local variable takes precedence over a global variable of the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable from the function.

The scope of a variable:

Global Variable: A global variable has global scope which means it can be defined anywhere in your code. More often than not we define global variable at or near the top of the file they are going to be used.

Local Variable: A local variable is visible or available only within a block of code or function where it is defined.

Let’s look at some code …

function add(num1, num2) {
    var sum = num1 + num2;
    console.log(sum);
    return sum;
}

// Call or Invoke the function and pass in some arguments
add(4, 6);  // Output --> 10;

What’s happening here…

  • We start with the function definition and name as before but this time we add two variables or what we refer to as parameters, num1 and num2.
  • Next we create a new variable sum and assign the value of adding num1 and num2.
  • We log the value of sum.
  • The value in sum is returned to where the function was called.

By adding parameters to the function definition, we make this function more versatile. Now we can add any two numbers that we pass in as arguments.

Wait, wait, wait… Parameters and Arguments? Are they the same, are they different?

Argument and Parameter are terms associated with functions:

  • Parameters are variables listed as part of the function definition.
  • Arguments are values passed to the function when it is invoked.
  • Parameters are defined once when we write the function.
  • A function can be called and passed various argument values.
  • Parameters can be thought of as placeholders for the values passed to the function.
// Defining a function, we pass a PARAMETER to the function and then use that VARIABLE within the function scope
function welcome(name) {
    console.log(“Welcome “ + name +!”);
}

// Call or Invoke the function and pass in an ARGUMENT (or value)
welcome(“Bill”);  // Output --> “Welcome Bill!”

Let’s talk a little more about returning from a function.

In JavaScript every function returns undefined unless otherwise specified. So, any function where we leave out the return statement when the JavaScript interpreter returns to where the function was invoked will return a result of undefined. This may be easiest to see when you use the built-in JavaScript Engine in a lot of modern web browsers.

return.png If the function does return a value, the JavaScript interpreter will return the value to the line where the function was invoked. The return statement ends function execution immediately. Meaning if you have any code or logic after the functions return statement, this code will never run.

Function Expression:

JavaScript Functions have an ability that not all programming languages offer. We have the ability to assign a function to a variable.

var result = function add(num1, num2) {
    return num1 + num2;
}

// Call or Invoke the function and pass in some arguments
result(10, 5);  // Output --> 15;

More often you will see this type of function express used with an anonymous or unnamed function:

var result = function(num1, num2) {
    return num1 + num2;
}

// Call or Invoke the function and pass in some arguments
result(10, 5);  // Output --> 15;

Let’s recap some of the benefits of using functions:

  • Using functions make your code more reusable. This also helps keep our code DRY.
  • Using functions, we can break our program down into smaller pieces or tasks.
  • Using functions can make our code base modular.
  • Following the basic guidelines helps increase readability and understanding of your code. This is helpful for debugging or learning from someone else’s code.

Hopefully this article on functions in JavaScript was useful to you. Thanks for reading, until next time!